Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to 2 dimension array in Javascript

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?

like image 680
pnichols Avatar asked Oct 22 '22 05:10

pnichols


2 Answers

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/

like image 87
Alex Avatar answered Oct 24 '22 04:10

Alex


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

like image 36
prime Avatar answered Oct 24 '22 02:10

prime