0

I have a regex:

var r = /^(\+?48)?\D*(?:(\d)\D*){9}/gi

Its purpose is to check whether a string contains (at least) 9 digits, mixed randomly with other non-digit characters. And I'm having this:

> r.test('    w3f23ev434r23f2e2323r23r48 12 345 62 89')
true
> r.test('    w3f23ev434r23f2e2323r23r48 12 345 62 89')
false
> r.test('    w3f23ev434r23f2e2323r23r48 12 345 62 89')
true
> r.test('    w3f23ev434r23f2e2323r23r48 12 345 62 89')
false

Why does this happen? Is a regex object instance mutable?

rishat
  • 8,206
  • 4
  • 44
  • 69
  • 2
    [Check out this question.](https://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results) – sdgluck Sep 21 '15 at 21:06
  • 1
    Yes, and it happens because you used the `/g` flag. (Also, `/i` is useless there). – melpomene Sep 21 '15 at 21:06
  • Still don't quite understand why `/g` works this way. As for `/i`, you're right, it was more out of habit rather that of practical value. – rishat Sep 21 '15 at 21:08
  • @RishatMuhametshin What did you think `/g` would do? – melpomene Sep 21 '15 at 21:10
  • Okay, got the idea from [the Q&A mentioned above](https://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results)! – rishat Sep 21 '15 at 21:11

0 Answers0