If I have str = "[[1,Warriors,NBA],[2,Kings,NBA],[3,Knicks,NBA]]"
how could I turn that into a array in JavaScript?
An array where each element of the array is an array itself.
Possible?
If I have str = "[[1,Warriors,NBA],[2,Kings,NBA],[3,Knicks,NBA]]"
how could I turn that into a array in JavaScript?
An array where each element of the array is an array itself.
Possible?
You can try this rudimentary function I put together for 2D arrays:
function customParse(data){
arr = []
for(var i = 0; i < str.length; i++){
if(str[i] == ','){
if(!isNaN(str[i-1])){
arr.push(',')
arr.push('"')
}else{
if(str[i-1] != "]"){
arr.push('"')
arr.push(',')
arr.push('"')
}else{
arr.push(',')
}
}
}else{
if(str[i] == ']' && str[i-1] != ']'){
arr.push('"')
}
arr.push(str[i])
}
}
return JSON.parse(arr.join(""))
}
str = "[[1,Warriors,NBA],[2,Kings,NBA],[3,Knicks,NBA]]"
result = customParse(str)
alert("Raw: "+result);
alert("Stringified: "+JSON.stringify(result));
A little dirty, but will do the trick. the "matches" variable would contain your array of arrays.
var str = "[[1,Warriors,NBA],[2,Kings,NBA],[3,Knicks,NBA]]";
var cleanStr = str.substring(1,str.length-1)
var matches = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((match = pattern.exec(cleanStr)) != null)
{
matches.push(match[1].split(","));
}
Additionally, if you have the option, just define the array in javascript.
var list = [[1,'Warriors','NBA'],['2','Kings','NBA'],[3,'Knicks','NBA']];
There are some javascript parsers written in javascript. See this:JavaScript parser in JavaScript, this:https://github.com/mishoo/UglifyJS, this:http://esprima.org/, this:http://marijnhaverbeke.nl/acorn/.
var array = JSON.parse("[" + str + "]");
or you can use .split()
, that will also end up with an Array of strings.