Luke T O'Brien
Luke T O'Brien

Reputation: 2845

Javascript RegExp different results from constructor and literal

I am looking into creating different Regular Expressions, looking for strong and medium strength user passwords, and I have noticed that the same expression gives different results (using lookaheads, backrefrence and negative lookaheads) depending on if I use the RegExp constructor or the literal syntax.

I have tested on IE and Firefox and created a little example here: http://jsfiddle.net/4z4gxxkL/

The reason I was using the RegExp constructor was that I am storing my expressions in JSON as strings - But in the case of passwords, I can use literal syntax.

All my other expressions are quite simple and produce expected results. Can somebody explain what is going on here? Is this a ECMAScript standards issue?

I always tend to use http://regexr.com/ to test my Regex

I discovered this discrepancy by preforming a test on "abc123" using RegExp("^(?=.*\d)(?=.*[a-zA-Z])(?!.*(.)\1).{5,}$", "g") that gave false, however a test using /^(?=.*\d)(?=.*[a-zA-Z])(?!.*(.)\1).{5,}$/g gave true

Upvotes: 1

Views: 269

Answers (1)

Amit Joki
Amit Joki

Reputation: 59252

When creating regex instance from RegExp constructor, you need to escape the \ with another \ as it is a escape-sequence.

The first one works right, because there is no \ in the String, whereas in others, it is there, unescaped.

Escaped Version

Upvotes: 5

Related Questions