Find the Javascript value inside the string, where String Contains the key / value

I have a line containing several pairs of parameters / values ​​in the form:

{type1|value1}{type2|value2} .....

I need to find if a particular type is inside the string (currently using indexOf search for "{type3|", for example), but then I need to get the value from this pair.

I could just put the line from the start point into another line, and then look for the location of the beginning and end of the value ("|" and "}"), but I'm sure there should be an easier way, possibly using Regex.

Any ideas please?

+4
source share
2 answers

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"
+3
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' }

, . .

+2

Source: https://habr.com/ru/post/1532641/


All Articles