简体   繁体   中英

How to Convert Comma Separated String into an Array in JavaScript

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

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" ]

You can filter empty strings after splitting:

 var str = "how;are;you;;doing;"; console.log(str.split(';').filter(Boolean));

You could do this

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM