RegExp.prototype.exec, RegExp.prototype.test, lastIndex
regexp.exec(str)
regexp.test(str)
regexp.lastIndexSearch a string with exec or test. With the g or y flag, lastIndex is the start position and is updated after each call.
| Parameter | Description |
|---|---|
str | The string to search. exec and test convert the argument to a string. |
Returns: exec returns a match array or null. test returns true or false. lastIndex is a number on the regex object.
- In the /a/g example on "abaca", lastIndex moves 1, 3, 5, then a failed exec resets it to 0.
- /foo/g on "foo" returns true with lastIndex 3, then false with lastIndex 0, then true again. Without g, both test calls return true and lastIndex stays 0.
- If lastIndex is 1, /a/y matches the "a" in "ba" but does not match "ab", because sticky matching cannot skip the character at lastIndex.
const re = /a/g;
console.log(JSON.stringify(re.exec("abaca")), re.lastIndex);
console.log(JSON.stringify(re.exec("abaca")), re.lastIndex);
console.log(JSON.stringify(re.exec("abaca")), re.lastIndex);
console.log(JSON.stringify(re.exec("abaca")), re.lastIndex);
const t = /foo/g;
console.log(t.test("foo"), t.lastIndex);
console.log(t.test("foo"), t.lastIndex);
console.log(t.test("foo"), t.lastIndex);
const noG = /foo/;
console.log(noG.test("foo"), noG.lastIndex);
console.log(noG.test("foo"), noG.lastIndex);
const sticky = /a/y;
sticky.lastIndex = 1;
console.log(JSON.stringify(sticky.exec("ba")), sticky.lastIndex);
const miss = /a/y;
miss.lastIndex = 1;
console.log(JSON.stringify(miss.exec("ab")), miss.lastIndex);Expected output
["a"] 1
["a"] 3
["a"] 5
null 0
true 3
false 0
true 3
true 0
true 0
["a"] 2
null 0Related: String replace and replaceAll