Reputation: 375
How to skip double ; and omit last ; from string;
function myFunction() {
var str = "how;are;you;;doing;";
var res = str.split(";");
console.log(res[3]);
console.log(res);
}
myFunction();
it should return how,are,you,doing
should be like console.log(res[3])
= it should says doing
not blank
Upvotes: 0
Views: 273
Reputation: 5084
Try this:-
var str = "how;are;you;;doing;";
var filtered = str.split(";").filter(function(el) {
return el != "";
});
console.log(filtered);
Output:
[ "how", "are", "you", "doing" ]
Upvotes: 5
Reputation: 31
Use split for converting in an array, remove blank space and then join an array using sep",".
function myFunction(str) {
var res = str.split(";");
res = res.filter((i) => i !== "");
console.log(res.join(","));
}
var str = "how;are;you;;doing;";
myFunction(str);
Upvotes: 0
Reputation: 11
The below function definition is in ES6:
let myFunction = () => {
let str = "how;are;you;;doing;";
return str.split(';').filter((el) => {
return el != "";
});
}
Now you can simply log the output of the function call.
console.log(myFunction());
Upvotes: 0
Reputation: 235
You could do this
var a = "how;are;you;;doing;";
a = a.split(';').filter(element => element.length);
console.log(a);
Upvotes: 1
Reputation: 5308
You can filter empty strings after splitting:
var str = "how;are;you;;doing;";
console.log(str.split(';').filter(Boolean));
Upvotes: 2