Datacrawler
Datacrawler

Reputation: 2876

JS Change string format

I have a string in the following format :

One,Two,Three,Four

and I want to change its format to "One","Two","Three","Four"

I tried the following :

var items = ['One,Two,Three,Four'];

var quotedAndCommaSeparated = '"' + items + '"';


document.write(quotedAndCommaSeparated);

which adds the double quotes at the beginning and at the end of the string. I don't want to use replace because there might be values that have a comma.

Is there a way to split the initial string and return the wanted one?

Upvotes: 0

Views: 135

Answers (2)

Golak Sarangi
Golak Sarangi

Reputation: 905

Try this

items[0].replace(/^|$/g, '"').replace(/,/g,'","')

Upvotes: 2

Chip Dean
Chip Dean

Reputation: 4302

This should give you what you want. Split on the commas and then rejoin using the delimiter you are looking for.

var quotedAndCommaSeparated = '"'+items[0].split(',').join('","')+'"'

Upvotes: 1

Related Questions