user2580016
user2580016

Reputation: 151

My regex doesn't work

I don't see the difference between creating a new regexp object or using /.../ because if I execute the following I get:

true false

alert(/^\d{4}$/.test(obj.value)+" "+(new RegExp("^\d{4}$")).test(obj.value));

thanks in advance

Upvotes: 0

Views: 195

Answers (1)

Pointy
Pointy

Reputation: 413826

When you create a RegExp object from a string, you have to account for the fact that the string constant syntax, like the RegExp syntax, treats \ as a special character:

alert(/^\d{4}$/.test(obj.value)+" "+(new RegExp("^\\d{4}$")).test(obj.value));

should work better. Note the \\ in the string version instead of a single \.

What goes on when you've got something like

var myRegExp = new RegExp( "blah blah \d blah blah" );

? First, the parser has to look at the low-lever parts of the expression, like the variable name, the = sign, the new, and so on. The string constant is one of those low-level basic elements of the expression. The parser has to turn that source code for a string into a runtime string value, and that involves reading the characters between the quotes. The \d in there will mean — to the string portion of the parser, remember — that the string should include a "d". (The "d" character isn't special, so \d really doesn't do anything interesting in a string, but the \ will be "eaten" nevertheless.)

So now we've got the basic building blocks of the expression, and so at runtime the RegExp constructor can be called with that string value the parser assembled. Now, it's time for the RegExp syntax analysis to take place. The RegExp parser won't see \d now, because the \ went away during the construction of the string constant.

Thus, by doubling the \ in the string passed to the RegExp constructor, you ensure that a single \ survives to the point at which the regular expression is actually interpreted as such. When you use the "native" regular expression syntax (/.../), then you only need one \ because the regular expression is only parsed once.

Upvotes: 4

Related Questions