0

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

Andreas
  • 21,535
  • 7
  • 47
  • 56
simon
  • 359
  • 1
  • 14
  • 1
    Does this answer your question? [How can I parse a CSV string with JavaScript, which contains comma in data?](https://stackoverflow.com/questions/8493195/how-can-i-parse-a-csv-string-with-javascript-which-contains-comma-in-data) – Justinas Mar 09 '21 at 08:29

5 Answers5

4

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" ]
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
TechySharnav
  • 4,869
  • 2
  • 11
  • 29
2

You can filter empty strings after splitting:

var str = "how;are;you;;doing;";

console.log(str.split(';').filter(Boolean));
gorak
  • 5,233
  • 1
  • 7
  • 19
1

You could do this

var a = "how;are;you;;doing;";
a = a.split(';').filter(element => element.length);

console.log(a);
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
JeannotMn
  • 184
  • 1
  • 9
0

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());
0

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);