Bronzato Bronzato - 7 months ago 10
Javascript Question

Retrieve values for custom parameters from a string

I need to retrieve values for custom parameters from a string.

Example of string:

aaa[111] bbb[222] ccc[333] ddd[444]


I need to get the value of
111
for the parameter
aaa
, etc...

The name of parameters are know in advance (here:
aaa
,
bbb
,
ccc
,
ddd
).

Maybe with regular expressions but I don't know how to proceed.

Answer

Try this

var output = {}; 
var str = "aaa[111] bbb[222] ccc[333] ddd[444]";
str.split(/\s+/).forEach(function(val){ 
  var key = val.substring(0, val.indexOf("[")); 
  var value = val.substring( val.indexOf("[") + 1, val.indexOf("]") ); 
  output[key] = value; 
});

document.body.innerHTML += JSON.stringify(output,0,4);

You can use this output variable to get the value against each parameter.

output["aaa"]; // outputs 111
Comments