0

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?

2
  • Why do you want to wrap them with quotes? What problem are you trying to solve? Commented Apr 4, 2017 at 16:40
  • there might be values that have a comma how do you determine wether a comma seperates two values or is part of one of them? Commented Apr 4, 2017 at 17:48

2 Answers 2

2

Try this

items[0].replace(/^|$/g, '"').replace(/,/g,'","')
Sign up to request clarification or add additional context in comments.

Comments

1

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('","')+'"'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.