Open up a browser console and execute the following code:
var foo = /foo/g;
Then,
foo.test("foo") // true
Then,
foo.test("foo") // false
If you continue to execute foo.test("foo"), you will see alternating true/false responses as if the var foo is actually being modified.
Anyone know why this is happening?
RegExp.prototype.test() The test() method executes a search for a match between a regular expression and a specified string. Returns true or false .
Use . test if you want a faster boolean check. Use . match to retrieve all matches when using the g global flag.
Regular expressions are a sequence of characters that are used for matching character combinations in strings for text matching/searching. In JavaScript, regular expressions are search patterns (JavaScript objects) from sequences of characters. RegExp makes searching and matching of strings easier and faster.
The test() method is a regular expression method. It searches a string for a pattern, and returns true or false, depending on the result. If it encountered the given pattern it returns true, else returns false.
Yes, that's how .test()
and .exec()
work when the regex is g
global. They start at the end of the last match.
You can observe the current last index on the regular expression object using the .lastIndex
property.
It's a writeable property, so you can reset it to 0
when/if you need. When the regex is run without finding a match, it automatically resets to 0
.
The regex keeps the position of the last test. This allows searching of long strings. You can reset this by setting lastIndex = 0;
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