带有变量的javascript正则表达式? [英] javascript regular expressions with variables?

查看:96
本文介绍了带有变量的javascript正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用变量作为查询来执行正则表达式。

I am trying to execute a regular expression with a variable as the query.

//This works
$('body *').replaceText(/\b(Toronto)/gi, nameWrapper );

我需要在变量中加入Toronto

I need to have "Toronto" in a variable

var query = "Toronto";
$('body *').replaceText(/\b( --  query VARIABLE HERE --  )/gi, nameWrapper );


推荐答案

您需要使用 RegExp 从字符串构建正则表达式:

You need to use RegExp to build a regular expression from a string:

var query = "Toronto";
$('body *').replaceText(RegExp("\\b(" + query + ")", "gi"), nameWrapper);

为了正确引用你的字符串,你可以使用:

And to quote your string properly, you can use this:

RegExp.quote = function(str) {
    return str.replace(/(?=[\\^$*+?.()|{}[\]])/g, "\\");
}

然后只需使用 RegExp.quote(查询)<构建正则表达式时,/ code>而不是查询

var query = "Toronto";
$('body *').replaceText(RegExp("\\b(" + RegExp.quote(query) + ")", "gi"), nameWrapper);

这篇关于带有变量的javascript正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆