Friday, September 19, 2025
HomeLanguagesJavascriptJavaScript RegExp lastIndex Property

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 =
Ā Ā Ā Ā Ā Ā Ā Ā "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()


Output

'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()


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, neveropen 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!
RELATED ARTICLES

Most Popular

Dominic
32301 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6666 POSTS0 COMMENTS
Nicole Veronica
11840 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11898 POSTS0 COMMENTS
Shaida Kate Naidoo
6781 POSTS0 COMMENTS
Ted Musemwa
7056 POSTS0 COMMENTS
Thapelo Manthata
6739 POSTS0 COMMENTS
Umr Jansen
6745 POSTS0 COMMENTS