Postanova Postanova - 4 months ago 15
jQuery Question

Need a regular expression to split string in javascript

I need some help with regular expressions in javascript. I've got a string like:

var S = '["abc","defg", "hij"]';


How could I split it in javascript to get
a[0]=abc
,
a[1]=defg
,
a[2]=hij
?
Because
var a = S.split(',');
just give me
a[0]=["abc"
and so on.
Thank you very much.

Answer

If you fix the quotes you use to delimit the string, then you can JSON.parse the string to an array and work with it as you need, like this:

var s = '["abc","defg", "hij"]';
var arr = JSON.parse(s);

console.log(arr);
console.log(arr[0]); // = 'abc'

Comments