Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
30
rated 0 times [  31] [ 1]  / answers: 1 / hits: 38206  / 12 Years ago, tue, april 10, 2012, 12:00:00

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



/bwordb/.test('a long text with the desired word amongst others'); // true
/bamongb/.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?


More From » regex

 Answers
38
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 /bwordb/.


[#86330] Monday, April 9, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
minab

Total Points: 701
Total Questions: 104
Total Answers: 91

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;