JavaScript RegExp lastIndex Property

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 = "zambiatek is the" + " computer science portal" + " for zambiatek"; 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() |
Output
'Geek' found. Indexes are: 4 12
Example-2: This example checks if the string contains “abc” in it.
Javascript
function geek() { let str = "zambiatek is" + " the computer science" + " portal for zambiatek"; 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() |
Output
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.
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



