I need to convert this string:
'"apple","banana","yellow peach","orange"'
to an array:
["apple","banana","yellow peach","orange"]
I need to convert this string:
'"apple","banana","yellow peach","orange"'
to an array:
["apple","banana","yellow peach","orange"]
Edit:
Squint's solution using JSON.parse()
is fine for this example, however, if there are nested quotation marks within your string, JSON.parse()
will error. For example:
var str = '"apple","banana","yellow peach","orange", "Dwayne "The Rock" Johnson"';
You will have to be aware of what your data could potentially look like. There may be instances where the inner quotations are needed and so you can't use a global replace of the quotation marks nor JSON.parse(), and you would need to do something like this:
var str = '"apple","banana","yellow peach","orange", "Dwayne "The Rock" Johnson"';
var arr = str.split(",").map(function (elem) {
return elem.trim().replace(/^"|"$/g, ''); // regex courtesy of torazaburo =)
});
console.log(arr);