3

I have a weird situation. I am using a Regex testing some strings. I would like to seal them to a class, like the following:

export class RegexPattern {
  static price = (/^\d*(\.\d{1,2})?$/g);
  static phone = (/^([0-9]{0,5}-)?[0-9]{10}$/g);
}

So lets say the input is '32'

But when I use it to test same strings twice, the first time will pass, the second time will fail, eg:

RegexPattern.price.test('32')  //return ture
RegexPattern.price.test('32')  // return false

But if I use it with bare Regex, without sealing:

(/^\d*(\.\d{1,2})?$/g).test('32')  //return ture
(/^\d*(\.\d{1,2})?$/g).test('32')  // return true

My question is why did this happen?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Stanley
  • 87
  • 1
  • 8
  • 1
    maybe you need to instantiate the class first like const regexPattern = new RegexPattern() – Joven28 Sep 20 '19 at 05:57
  • @Joven28 I don't think it needs initiate the class. And also I tried that, it will return undefined. – Stanley Sep 20 '19 at 06:03

1 Answers1

8

The RegExp object keeps track of the lastIndex where a match occurred, so on subsequent matches it will start from the last used index, instead of 0.

If you don't want to manually reset lastIndex to 0 after every test, just remove the g flag.

When you test the regex individually, you're actually creating a new regexp object with every invocation, that's why that works. If you were doing:

'use strict';

const regex = /^\d*(\.\d{1,2})?$/g;

console.log(regex.test(32));
console.log(regex.test(32));

You would get true, false, too.

Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72