[英]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我如何在“obj.name 名称”和“g233”字符串中获取 str 中的“变量值”/“对象属性”
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
而不将"
obj.age
,可以搜索以下正则表达式。
[^"](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 https://regex101.com/r/DTTesL/1
If yoy want to ES2015 / ES6 feature called Template Literals use this syntax:如果 yoy 想要 ES2015 / ES6 功能称为模板文字,请使用以下语法:
`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 +
.这将匹配刚好在 beginig (
^
) 或+
号之后、结尾 ( $
) 或另一个加号+
之前的任何变量。 [a-z_][\\w.]*
means that it have to start with a letter or _
and can contain numbers, letters, _
and .
[a-z_][\\w.]*
表示它必须以字母或_
开头,并且可以包含数字、字母、 _
和.
. .
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.