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.
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.
Share Improve this question edited Mar 9, 2012 at 19:40 Pops 30.9k37 gold badges137 silver badges153 bronze badges asked Jun 1, 2011 at 0:25 Scott Scott 851 silver badge8 bronze badges 1-
Arrays use
[
, not{
. – SLaks Commented Jun 1, 2011 at 0:27
4 Answers
Reset to default 5It 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)
What? Is everyone insane?!
var array = ['string 1', 'string 2', 'string 3'];
You can use eval()...
var myArray = eval("['string 1', 'string 2', 'string 3']");
alert(myArray[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);
}