简体   繁体   中英

javascript regexp get no quotes params

eg:

var str = '2+3+name+"obj.name name"+"g233"';

how can i get the "variable values"/"object properties" within str in place "obj.name name" and "g233" strings


the example output comment below is what i want, if there has a best way to realize it;

 var age = 20; var str = '1 + 2 + 3 + age + "age"'; // the output is 1 + 2 + 3 + 20 + "age"; var obj = { age: 30 }; str = '1 + 2 + 3 + "age" + obj.age + "obj.age"'; // the output is 1 + 2 + 3 + "age" + 30 + "obj.age";

the exmple is what i want.

You can search for the following regular expression, if you want to match obj.age or age without surrounding " .

[^"](obj\.age|age)[^"]

 var str1 = '1 + 2 + 3 + age + "age"'; var str2 = '1 + 2 + 3 + "age" + obj.age + "obj.age"'; var regex = /[^"](obj\\.age|age)[^"]/g; console.log(str1.match(regex)); console.log(str2.match(regex));

Try this link if you need regexp

https://regex101.com/r/DTTesL/1

If yoy want to ES2015 / ES6 feature called Template Literals use this syntax:

`String text ${expression}`

You even can make it like this:

'I want to replace the $age'.replace('$age', age)
/(?:^|\+)\s*([a-z_][\w.]*)\s*($|\+)/gi

this will match any variable that is right at the beginig ( ^ ) or after a + sign, and before the end ( $ ) or another plus sign + . [a-z_][\\w.]* means that it have to start with a letter or _ and can contain numbers, letters, _ and . .

EXAMPLE:

 var regex = /(?:^|\\+)\\s*([a-z_][\\w.]*)\\s*(?:\\+|$)/g; var str = '1+name + obj.ko + "lmo" + f98 + "g99"+v'; var matches = []; var r; while(r = regex.exec(str)){ // should come backwards one step to cover the just-consumed + regex.lastIndex--; matches.push(r[1]); } console.log(matches);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM