2

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.

1
  • Arrays use [, not {. Commented Jun 1, 2011 at 0:27

4 Answers 4

5

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)

Sign up to request clarification or add additional context in comments.

Comments

3

What? Is everyone insane?!

var array = ['string 1', 'string 2', 'string 3'];

3 Comments

the thing about doing that is the string gets read as individual characters like array[0] gives me [ and array[1] gives me '
@Scott - you're not supposed to split or otherwise parse this - this is JSON. If you output this exact line you will get a javascript array called 'array'
+1 assuming the array 'string' is available when the page is first generated as compared to being returned from an Ajax call - which of course the OP didn't mention.
2

You can use eval()...

var myArray = eval("['string 1', 'string 2', 'string 3']");
alert(myArray[0]);

4 Comments

(new Function('return ' + myArray))
@Scott It may work, but the other two answers are safer, more efficient, and more modern.
guys seriously, I don't mean to be a **** but this is not sensible (see my answer)
You guys are right, eval() can be dangerous and if you are unsure about the source, I'd recommend going with JSON.
0
var array = string.split("','");
if(array.length == 1)
{
    //deal with empty or one element array
}
else{
    array[0] = array[0].substring(3);
    array[array.length() - 1] = array[array.length() - 1].substring(0, array[array.length() - 1].length() - 3);
}

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.