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.

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

2 Comments

Hi Hoacheng +1 for your good answer. But still I am confused with the concept. can you please describe it in simple way.
@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.
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.

Comments

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.

Comments

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 Comment

The global modifier is not only useful for substitutions.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.