5

I've got this string which needs to be converted to an array:

var string = "[[Restaurants], [Restaurants], [Restaurants], [Caterers, Foods - Take-out]]";

I then need to be able to access its value like so:

var foo = arr[0];  //returns "Restaurant"
var bar = arr[3];  //returns "Caterers, Foods - Take-out"

I tried removing the first and last characters ( "[" and "]" ) but I was still left with a problem when splitting on "," because some of the value have commas inside them. Any ideas?

4

3 回答 3

2

您可以使用split方法和map方法的组合。split创建数组并map通过返回一个新的来清理它Array

var string = '[[Restaurants], [Restaurants], [Restaurants], [Caterers, Foods - Take-out]]';

var items = string.split('],').map(
    function(s) { return s.replace(/(\[\[| \[|\]\])/g, ''); }
);

http://jsfiddle.net/4LYpr/

于 2013-07-11T19:56:30.807 回答
1

由于您正在拆分并尝试创建一个数组,因此首先删除第一个(“[[”)和最后一个(“]]”),然后将字符串拆分为(“],[”)。

于 2013-07-11T20:00:07.567 回答
0

简单的:

> a = "[[Restaurants], [Restaurants], [Restaurants], [Caterers, Foods - Take-out]]"
> b = a.slice(1).split(",")
> newB = []
> for (i=0;i < b.length;i++) {
    formatted = b[i].trim().slice(1,-2);
    newB.push(formatted);
}
于 2013-07-11T20:34:54.183 回答