Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression with javascript

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.

like image 389
Workonphp Avatar asked Jan 31 '13 03:01

Workonphp


People also ask

Does JavaScript support regular expression?

In JavaScript, regular expressions are often used with the two string methods: search() and replace() . The search() method uses an expression to search for a match, and returns the position of the match. The replace() method returns a modified string where the pattern is replaced.

How do you evaluate a regular expression in JavaScript?

JavaScript | RegExp test() Method The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false. Where str is the string to be searched.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


2 Answers

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.

like image 64
Haocheng Avatar answered Sep 23 '22 10:09

Haocheng


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.

like image 39
Ja͢ck Avatar answered Sep 23 '22 10:09

Ja͢ck