1

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

2
  • 2
    post your regex and the input here. Commented Feb 9, 2015 at 14:37
  • For an in-depth discussion of whats going on here, see my answer to a very similar question: Building regexp from JS variables not working Commented Feb 9, 2015 at 15:00

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

@LukeTO'Brien happens :-)
You deserve a cookie.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.