The following code writes “response” as expected:
var str = "Would you like to have responses";
var pattern = "Response";
document.write(str.match(new RegExp(pattern,'gi')));
but when I add a specifier like \b, the following writes “null”:
var str = "Would you like to have responses";
var pattern = "\bResponse";
document.write(str.match(new RegExp(pattern,'gi')));
How can I make it work?
Interestingly, both of the following works
document.write(str.match(new RegExp(/Response/gi)));
document.write(str.match(new RegExp(/\bResponse/gi)));
but I want to use new RegExp(pattern,modifiers); syntax.
A backslash has a special meaning in a string, it’s the escape character. When you want to create a Regular expression from a string, backslashes has to be escaped.
In the case when the escaped characters have the same meaning, you’re not going to notice it:
both work. However,
\bdoes not have such a meaning in a string.new RegExp("\bResponse");becomes/Response/(\bis a backspace character, which does not represent a visible character). When an escape does not have a special meaning, the backslash is dropped.