admin管理员组文章数量:1332339
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
2 Answers
Reset to default 8You 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);
本文标签: regexjavascript regular expressions with variablesStack Overflow
版权声明:本文标题:regex - javascript regular expressions with variables? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742329313a2454364.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论