JavaScript | 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.
<!DOCTYPE html> <html> <head> <title> lastIndex Property </title> </head> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2> lastIndex Property </h2> <button onclick="geek()"> Click it! </button> <script> function geek() { var str = "GeeksforGeeks is the"+ " computer science portal"+ " for geeks"; var patt1 = /Geek/g; var ans = "'Geek' found. Indexes are: "; // check "geek" in string. while (patt1.test(str) == true) { ans += patt1.lastIndex + " "; } alert(ans); } </script> </body> </html> |
Output:
Before clicking the button:

After clicking the button:

Example-2: This example checks if the string contains “abc” in it.
<!DOCTYPE html> <html> <head> <title> lastIndex Property </title> </head> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2>lastIndex Property</h2> <button onclick="geek()"> Click it! </button> <script> function geek() { var str = "GeeksforGeeks is"+ " the computer science"+ " portal for geeks"; var patt1 = /abc/g; var ans = "'Geek' found. Indexes are: "; var ans1 = "'Geek' found. Indexes are: "; var len = ans.length; // check "geek" in string. while (patt1.test(str) == true) { ans1 += patt1.lastIndex + " "; } var x = ans1.length; if (len === x) alert("RegExp is not "+ "present in the string."); else alert(ans1); } </script> </body> </html> |
Output:
Before clicking the button:

After clicking the button:

Supported Browsers: The browsers supported by JavaScript lastIndex Property are listed below:
- Google Chrome
- Apple Safari
- Mozilla Firefox
- Opera
- Internet Explorer
Recommended Posts:
- JavaScript | Math.LN2 property
- JavaScript | global Property
- JavaScript | Cursor property
- JavaScript | undefined Property
- JavaScript | Math.PI Property
- How to remove CSS property using JavaScript?
- JavaScript | multiline Property
- JavaScript | Infinity Property
- JavaScript | Error name Property
- Javascript | MouseEvent which Property
- JavaScript | source Property
- JavaScript | MouseEvent shiftKey Property
- JavaScript | arrayBuffer.byteLength property
- JavaScript | Get the index of an object by its property.
- Javascript | MouseEvent ctrlKey Property
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



