[英]How can I use a variable inside a RegExp?
var string = "This is a string";
var key = "Th";
var patt = new RegExp(/\b key /, "i");
if(patt.test(string)){
alert("true");
}
How can I escape \\b so I can use the key
variable? 如何转义\\ b以便可以使用key
变量?
Thanks in advance! 提前致谢!
Don't use a regular expression literal when using the RegExp constructor. 使用RegExp构造函数时,请勿使用正则表达式文字。
When you want a \\
in a string literal, you have to escape it as \\\\
. 如果要在字符串文字中使用\\
,则必须以\\\\
对其进行转义。
Here's the code : 这是代码:
var patt = new RegExp("\\b " + key + " ", "i");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.