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
  • 20,797
  • 7
  • 44
  • 55
simon
  • 277
  • 1
  • 8
  • 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,282
  • 2
  • 15
  • 28
TechySharnav
  • 3,801
  • 2
  • 11
  • 25
2

You can filter empty strings after splitting:

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

console.log(str.split(';').filter(Boolean));
Rajan
  • 4,939
  • 1
  • 5
  • 17
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,282
  • 2
  • 15
  • 28
JeannotMn
  • 176
  • 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);