简体   繁体   English

将变量传递给正则表达式

[英]Passing variable to regular expression

I have a regular expression 我有一个正则表达式

var p = /\bj[^\b]*?\b/gi;

I need to make the 'j' a variable value, but when i do the following;- 我需要将'j'设为变量值,但是当我执行以下操作时:-

var p = new RegExp('\\b'+'${0}'+'[^\\b]*?\\b', 'gi');

I get error - 我收到错误-

Uncaught SyntaxError: Invalid regular expression: /\b${0}[^\b]*?\b/: Nothing to repeat 

Any help appreciated. 任何帮助表示赞赏。

Thank you 谢谢

I think you want the following: 我认为您需要以下条件:

var p = new RegExp('\\b'+${0}+'[^\\b]*?\\b', 'gi');

With the quotes around ${0} you are just constructing a string with those characters, instead of inserting the variable value. 使用${0}前后的引号,您仅用这些字符构造一个字符串,而不是插入变量值。

Putting a variable within quotation marks as you have done with '${0}' is going to cause that to be treated as a string. '${0}'所做的操作一样,将变量放在引号内将导致该变量被视为字符串。 If you remove the quotation marks from around it then it will be treated as a variable. 如果删除引号周围的引号,则它将被视为变量。

Sorry guys, I should have been more clear, the value '{0}' is a token that will be replaced and not a variable. 抱歉,我应该更加清楚,值'{0}'是将被替换的令牌,而不是变量。 The error was occurring because '{' and '}' are special characters in regular expressions. 发生错误是因为'{'和'}'是正则表达式中的特殊字符。

So changing the token pattern fixed the problem 因此,更改令牌模式可以解决问题

var p = new RegExp('\\b'+'%text%'+'[^\\b]*?\\b', 'gi');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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