JavaScript regex test if string contains a specific word (with variable)

I have a regex to check if a string contains a specific word. It works as expected:

/\bword\b/.test('a long text with the desired word amongst others'); // true /\bamong\b/.test('a long text with the desired word amongst others'); // false 

But I need a word that needs to be checked in a variable. Using new RegExp does not work correctly, it always returns false :

 var myString = 'a long text with the desired word amongst others'; var myWord = 'word'; new RegExp('\b' + myWord + '\b').test(myString); // false myWord = "among"; new RegExp('\b' + myWord + '\b').test(myString); // false 

What is wrong here?

+8
javascript regex string-comparison
source share
1 answer
 var myWord = 'word'; new RegExp('\\b' + myWord + '\\b') 

You need to double escape \ when creating a regular expression from a string.


This is because \ starts an escape sequence in a string literal, so it never gets into a regular expression. When you execute \\ , you include the literal character '\' in the string, which makes the regular expression /\bword\b/ .

+20
source share

All Articles