68 of 264 menu

lastIndexOf method

The lastIndexOf method searches for the last occurrence of a substring in a string. In this case, it is necessary to pay attention to the character case specified in the first parameter. The search is performed from the end of the string. The method will return the position of the first match from the end, and if it is not found, it will return -1. As the second optional parameter, you can pass the character number from where the search should start.

Syntax

string.lastIndexOf(what to search, [where to start search]);

Example

Let's find the position of the last occurrence of a substring:

let str = 'ab cd cd cd ef'; let res = str.lastIndexOf('cd'); console.log(res);

The code execution result:

9

Example

Let's set the search start position:

let str = 'ab cd cd cd ef'; let res = str.lastIndexOf('cd', 8); console.log(res);

The code execution result:

6

See also

  • the startsWith method
    that checks the start of a string
  • the endsWith method
    that checks the end of a string
  • the indexOf method
    that searches for the first occurrence of a substring
  • the includes method
    that searches for a string
  • the at method
    that searches for a string character
enru