16

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 the word which is about to be checked in a variable. Using new RegExp does not work properly, 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?

0

1 Answer 1

33
var myWord = 'word';
new RegExp('\\b' + myWord + '\\b')

You need to double escape the \ when building a regex from a string.


This is because \ begins an escape sequence in a string literal, so it never makes it to the regex. By doing \\, you're including a literal '\' character in the string, which makes the regex /\bword\b/.

Sign up to request clarification or add additional context in comments.

3 Comments

Figured it out at the same time you posted your answer. Thank you.
@Uri: Not sure what that has to do with this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.