Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variables inside Regular Expression in Javascript

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.

like image 933
Andre Garzia Avatar asked May 06 '11 20:05

Andre Garzia


2 Answers

\ 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).

like image 97
Quentin Avatar answered Oct 23 '22 01:10

Quentin


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

like image 29
Edgar Villegas Alvarado Avatar answered Oct 23 '22 01:10

Edgar Villegas Alvarado