Smurfette Smurfette - 10 months ago 34
Javascript Question

Why do regex constructors need to be double escaped?

In the regex below,

denotes a space character. I imagine the regex parser, is going through the string and sees
and knows that the next character is special.

But this is not the case as double escapes are required.

Why is this?

var res = new RegExp('(\\s|^)' + foo).test(moo);

Is there a concrete example of how a single escape could be mis-interpreted as something else?


You are constructing the regular expression by passing a string to the RegExp constructor.

You need to escape the \ so that your string literal can express it as data before you transform it into a regular expression.