最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - javascript regular expressions with variables? - Stack Overflow

programmeradmin1浏览0评论

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

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

I need to have "Toronto" in a variable

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

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

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

I need to have "Toronto" in a variable

var query = "Toronto";
$('body *').replaceText(/\b( --  query VARIABLE HERE --  )/gi, nameWrapper );
Share Improve this question asked Nov 21, 2010 at 8:34 Ian VinkIan Vink 68.8k107 gold badges352 silver badges567 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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, "\\");
}

Then just use RegExp.quote(query) instead of query when building the regular expression:

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

Try like this:

var query = 'Toronto';
var regex = new RegExp('\\b(' + query + ')', 'gi');
$('body *').replaceText(regex, nameWrapper);
发布评论

评论列表(0)

  1. 暂无评论