views:

104

answers:

1

I have this as data input (it's dynamic so it can be 1 up to 5 brackets in the same string)

data["optionBase"] = {} //declaration
data["optionBase"]["option"] = {} //declaration
data["optionBase"]["option"][value] = {} //declaration
data["optionBase"]["option"][value]["detail"] = somethingHere

Each line comes as a string, not as an array or any other type of javascript object. How can i get an array out of that string containing something like this:

Line 1:

result[0] = "optionBase"

Line 2:

result[0] = "optionBase"
result[1] = "option"

Line 3:

result[0] = "optionBase"
result[1] = "option"
result[2] = value

Line 4:

result[0] = "optionBase"
result[1] = "option"
result[2] = value
result[3] = "detail"
+1  A: 
var s1 = 'data["optionBase"] = {} //declaration';
var s2 = 'data["optionBase"]["option"] = {} //declaration';
var s3 = 'data["optionBase"]["option"][value] = {} //declaration';
var s4 = 'data["optionBase"]["option"][value]["detail"] = somethingHere';
var a = [s1, s2, s3, s4];
var regex = /data\[([^\]]+)\](?:\[([^\]]+)\])?(?:\[([^\]]+)\])?(?:\[([^\]]+)\])?/;
for(var i = 0; i < 4; i++)
{
  var result = a[i].match(regex);
  //result[0] contains the whole matched string
  for(var j = 0; j < 5; j++)
    console.log(result[j]);
}

If you want to make it dynamic, you can extract the string and split around ][

var s = 'data["optionBase"]["option"][value]["detail"] = somethingHere';
var m = s.match(/data((?:\[[^\]]+\])+)/);
var substr = m[1].substring(1, m[1].length - 1);
var array = substr.split("][");
console.log(array);
Amarghosh
This looks good, i think it's close to what i want up to 90%, but is there a way to make the regexp dynamic? with your regexp it's limited to 4 brackets right? if the data input grows it will not get the value. If it's not possible guess i'll take this solution
Kusanagi2k
@Kusanagi See the update
Amarghosh
Excellent, works like a charm, however i found out that using m[1].length - 1 instead of -2 gives me exactly what i have inside the brackets, with -2 it removed the last " of the value. Thanks for your help
Kusanagi2k
@Kus Fixed it. I was confused between string.substring and string.substr it seems.
Amarghosh
Excellent, thanks again, really nice work!
Kusanagi2k