9

I have following code in java script

    var regexp = /\$[A-Z]+[0-9]+/g;
    for (var i = 0; i < 6; i++) {
        if (regexp.test("$A1")) {
            console.log("Matched");
        }
        else {
            console.log("Unmatched");
        }
    }

Please run it on your browser console. It will print alternative Matched and Unmatched. Can anyone tell the reason for it.

1

4 Answers 4

4

After call test on a string, the lastIndex pointer will be set after the match.

Before:
$A1
^

After:
$A1
   ^

and when it comes to the end, the pointer will be reset to the start of the string.

You can try '$A1$A1', the result will be

Matched
Matched
Unmatched
...

This behavior is defined in 15.10.6.2, ECMAScript Language Spec.

Step 11. If global is true, a. Call the [[Put]] internal method of R with arguments "lastIndex", e, and true.

2
  • Hi Hoacheng +1 for your good answer. But still I am confused with the concept. can you please describe it in simple way.
    – Workonphp
    Jan 31, 2013 at 5:08
  • @Workonphp There's a pointer lastIndex when using g flag on your RE, which means the place matched last time will be stored. This behavior causes your problem.
    – Haocheng
    Jan 31, 2013 at 5:18
1

I've narrowed your code down to a simple example:

var re = /a/g, // global expression to test for the occurrence of 'a'
s = 'aa';     // a string with multiple 'a'

> re.test(s)
  true
> re.lastIndex
  1
> re.test(s)
  true
> re.lastIndex
  2
> re.test(s)
  false
> re.lastIndex
  0

This only happens with global regular expressions!

From the MDN documentation on .test():

As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

0

This is because you use the global flag g, every time you called .test, the .lastIndex property of the regex object is updated.

If you don't use the g flag, then you could see the different result.

0

The 'g' in line one is not correct, you are not performing a substitution here, but a match, remove it and you will get your expected behavior.

var regexp = /\$[A-Z]+[0-9]+/g; should be: var regexp = /\$[A-Z]+[0-9]+/

1
  • The global modifier is not only useful for substitutions. Jan 31, 2013 at 4:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.