How to use variables inside regex in javascript

I want to create RegEx in JavaScript that matches the word but is not part of it. I think something like \ bword \ b works well for this. My problem is that this word is not known in advance, so I would like to collect a regular expression using a variable containing a word that will match something line by line:

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 certain words in the paragraph with a span tag. Can anybody help me?

PS: I am using jQuery.

+8
javascript jquery regex
source share
4 answers

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

Since you are building a regex from strings, you need to escape \ in them.

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

should do the trick, although I have not tested it.

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

+13
source share

You do not avoid backslashes. So you should have:

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

Also, you should avoid special characters in the word, because you don't know if they can have special regular expression characters.

Hope this helps. Greetings

+3
source share

And do not write expressions to the regexp variable, because this will not work!

Example (does not work):

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

An example that returns a string as expected:

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

Use this

 r = "(\\\b" +word+ "\\\b)" 
0
source share

All Articles