Open In App

JavaScript RegExp lastIndex Property

Improve
Improve
Like Article
Like
Save
Share
Report

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 =
        "GeeksforGeeks is the" +
        " computer science portal" +
        " for geeks";
 
    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 =
        "GeeksforGeeks is" +
        " the computer science" +
        " portal for geeks";
 
    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.



Last Updated : 02 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads