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?
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/
Since you are splitting and trying to make an array first remove the first("[[") and last ("]]") then split the string by ("], [").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With