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
  • 1
    your 'var string = ....' statement is not valid javascript. Commented Jul 11, 2013 at 19:50
  • 2
    this is not a string -->>> var string = [[Restaurants], [Restaurants], [Restaurants], [Caterers, Foods - Take-out]] Commented Jul 11, 2013 at 19:52
  • I think you mean var arr = ["Restaurants", "Restaurants", "Restaurants", "Caterers, Foods - Take-out"] Commented Jul 11, 2013 at 19:55
  • Sorry, I forgot the quotes.... It is a string. Commented Jul 11, 2013 at 20:08

3 Answers 3

2

You could use a combination of the split method and the map method. split creates the array and map cleans it up by returning a new 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/

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

Comments

1

Since you are splitting and trying to make an array first remove the first("[[") and last ("]]") then split the string by ("], [").

Comments

0

Easy:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.