regex - javascript regular expressions with variables? - Stack Overflow

I am trying to execute a regular expression with a variable as the query.This works$('body *�

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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742329313a4423389.html

相关推荐

  • regex - javascript regular expressions with variables? - Stack Overflow

    I am trying to execute a regular expression with a variable as the query.This works$('body *�

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信