You can use:
s='{type1|value1}{type2|value2}{type3|value3}{foo|bar}'
search='type3';
m = s.match(new RegExp('\\{' + search + '\\|([^}]+)'));
if (m)
val=m[1]; //=> "value3"
Question
I have a string that contains a number of parameter/value pairs in the form:
{type1|value1}{type2|value2} .....
I need to find if a specific type is within the string (currently using indexOf searching for "{type3|"
for example) but then I need to retrieve the value from that pair.
I could just place the string from the start point into another string, then search for the location of the start and end of the value ("|" and "}")
, but I am sure there ought to be a simpler way, probably using Regex.
Any ideas please?
Solution
You can use:
s='{type1|value1}{type2|value2}{type3|value3}{foo|bar}'
search='type3';
m = s.match(new RegExp('\\{' + search + '\\|([^}]+)'));
if (m)
val=m[1]; //=> "value3"
OTHER TIPS
var my_string = "{type1|value1}{type2|value2}";
var regEx = /\{(.*?)\}/g,
match, object = {};
while ((match = regEx.exec(my_string)) !== null) {
var key_value = match[1].split("|");
object[key_value[0]] = key_value[1];
}
console.log(object);
# { type1: 'value1', type2: 'value2' }
Convert the string to an object like this. Now, lookups are trivial and faster.