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.
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.
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.
[] 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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With