The lastIndex Property in JavaScript is used to specify the index at which to start the next match. If āgā modifier is not present this property will not work. It can be used to return the position of character immediately after the previous match.
Syntax:
RegexObj.lastIndex
Example 1: This example checks if the string contains āGeekā in it.
Javascript
function geek() { Ā Ā Ā Ā let str = Ā Ā Ā Ā Ā Ā Ā Ā "neveropen is the" + Ā Ā Ā Ā Ā Ā Ā Ā " computer science portal" + Ā Ā Ā Ā Ā Ā Ā Ā " for neveropen" ; Ā
Ā Ā Ā Ā let patt1 = /Geek/g; Ā Ā Ā Ā let ans = "'Geek' found. Indexes are: " ; Ā Ā Ā Ā // check "geek" in string. Ā Ā Ā Ā while (patt1.test(str) == true ) { Ā Ā Ā Ā Ā Ā Ā Ā ans += patt1.lastIndex + " " ; Ā Ā Ā Ā } Ā Ā Ā Ā console.log(ans); } geek() |
'Geek' found. Indexes are: 4 12
Example-2: This example checks if the string contains āabcā in it.
Javascript
function geek() { Ā Ā Ā Ā let str = Ā Ā Ā Ā Ā Ā Ā Ā "neveropen is" + Ā Ā Ā Ā Ā Ā Ā Ā " the computer science" + Ā Ā Ā Ā Ā Ā Ā Ā " portal for neveropen" ; Ā
Ā Ā Ā Ā let patt1 = /abc/g; Ā Ā Ā Ā let ans = Ā Ā Ā Ā Ā Ā Ā Ā "'Geek' found. Indexes are: " ; Ā Ā Ā Ā let ans1 = Ā Ā Ā Ā Ā Ā Ā Ā "'Geek' found. Indexes are: " ; Ā Ā Ā Ā let len = ans.length; Ā
Ā Ā Ā Ā // check "geek" in string. Ā Ā Ā Ā while (patt1.test(str) == true ) { Ā Ā Ā Ā Ā Ā Ā Ā ans1 += patt1.lastIndex + " " ; Ā Ā Ā Ā } Ā Ā Ā Ā let x = ans1.length; Ā Ā Ā Ā if (len === x) Ā Ā Ā Ā Ā Ā Ā Ā console.log( "RegExp is not " + Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā "present in the string." ); Ā Ā Ā Ā else Ā Ā Ā Ā Ā Ā Ā Ā console.log(ans1); } geek() |
RegExp is not present in the string.
Supported Browsers: The browsers supported by JavaScript lastIndex Property are listed below:
- Google Chrome
- Apple Safari
- Mozilla Firefox
- Opera
- Internet Explorer
We have a complete list of Javascript RegExp expressions, to check those please go through this JavaScript RegExp Reference article.