Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate array from comma-separated value string

Tags:

javascript

I have a string that is sent to my JavaScript via PHP that looks like this:

var string = "[ 'string 1','string 2 ','string 3' ]"

I want to split this string and get rid of the symbols [, ] and ' to produce the array

var array = {
    string 1, 
    string 2,
    string 3,
}

My current method uses a bunch of replaces, splits and loops. It seems very inefficient, and I want a better/more efficient method.

like image 736
Scott Avatar asked Jul 27 '26 06:07

Scott


1 Answers

It sounds like you're trying to parse a JSON string.

Use a JSON parser:

var array = JSON.parse(str);

For older browsers, you should include a JSON parser. (Newer browsers have it built-in)

like image 99
SLaks Avatar answered Jul 28 '26 19:07

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!