Open In App

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.




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.




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:

We have a complete list of Javascript RegExp expressions, to check those please go through this JavaScript RegExp Reference article.


Article Tags :