javascript - Generate array from comma-separated value string - Stack Overflow

I have a string that is sent to my JavaScript via PHP that looks like this:var string = "[ 's

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
Add a ment  | 

4 Answers 4

Reset to default 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)

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);
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744771151a4592766.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信