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

jquery - How to use variables inside Regular Expression in Javascript - Stack Overflow

programmeradmin2浏览0评论

I want to build a RegEx in JavaScript that matches a word but not part of it. I think that something like \bword\b works well for this. My problem is that the word is not known in advance so I would like to assemble the regular expression using a variable holding the word to be matched something along the lines of:

r = "\b(" + word + ")\b";
reg = new RegExp(r, "g");
lexicon.replace(reg, "<span>$1</span>"

which I noticed, does not work. My idea is to replace specific words in a paragraph with a span tag. Can someone help me?

PS: I am using jQuery.

I want to build a RegEx in JavaScript that matches a word but not part of it. I think that something like \bword\b works well for this. My problem is that the word is not known in advance so I would like to assemble the regular expression using a variable holding the word to be matched something along the lines of:

r = "\b(" + word + ")\b";
reg = new RegExp(r, "g");
lexicon.replace(reg, "<span>$1</span>"

which I noticed, does not work. My idea is to replace specific words in a paragraph with a span tag. Can someone help me?

PS: I am using jQuery.

Share Improve this question asked May 6, 2011 at 20:45 Andre GarziaAndre Garzia 9832 gold badges11 silver badges19 bronze badges 2
  • If you think \bword\b will work, why are you creating it as \b(word)\b? – Jaymz Commented May 6, 2011 at 20:47
  • because I want to capture the given word which will not always be "word". – Andre Garzia Commented May 6, 2011 at 22:12
Add a comment  | 

4 Answers 4

Reset to default 13

\ is an escape character in regular expressions and in strings.

Since you are assembling the regular expression from strings, you have to escape the \s in them.

r = "\\b(" + word + ")\\b";

should do the trick, although I haven't tested it.

You probably shouldn't use a global for r though (and probably not for reg either).

You're not escaping the backslash. So you should have:

r = "\\b(" + word + ")\\b"; //Note the double backslash
reg = new RegExp(r, "g");

Also, you should escape special characters in 'word', because you don't know if it can have regex special characters.

Hope this helps. Cheers

And don't write expressions in the regexp variable, because it does not work!

Example(not working):

 var r = "^\\w{0,"+ maxLength-1 +"}$";    // causes error
 var reg = new RegExp(r, "g");

Example, which returns the string as expected:

 var m = maxLength - 1;
 var r = "^\\w{0,"+ m +"}$";
 var reg = new RegExp(r, "g");

Use this

r = "(\\\b" +word+ "\\\b)" 
发布评论

评论列表(0)

  1. 暂无评论