juju
juju

Reputation: 326

How to split a string with a comma as delimiter to a string that looks like an array with string elements?

I need a string like: "one, two, thee, four" to be changed into string like: "["one", "two", "three", "four"]"

So, I've been trying to come up with a solution that tackles most use-cases, but without success. So far I came up with the following:

 var splitString = <mystring>.split(', ');
 var stringWithQuotes = `"` + stringSplit.join(`", "`) + `"`;

Though an input such as "one,two,thee,four" (without spaces) in between won't split the string into parts. The square brackets are missing aswell.

Any ideas?

Upvotes: 1

Views: 67

Answers (2)

gLorenzini
gLorenzini

Reputation: 37

My solution is:

    var mystr = "one, two, thee, four";
    var myarr = mystr.split(", ");
    var myJSON = JSON.stringify(myarr);
    console.log(myJSON);

Return the string '["one", "two", "three", "four"]'

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89364

You can split on a regular expression to allow optional whitespace between tokens.

let str = "one,two,thee,four";
let parts = str.split(/,\s*/);
let res = '["' + parts.join('", "') + '"]';
console.log(res);

Upvotes: 2

Related Questions