JavaScript Code

JavaScript String lastIndexOf()


String lastIndexOf()

str.lastIndexOf(search, start)
  • str is a string
  • search is a string
  • start is an integer, index position

lastIndexOf() method returns the index/position of the last occurrence of search string in the string str . searching happens from the trail end of the string str. if start is provided, searching the string str happens from that index at the end of the string str

Examples

1. find index of last occurrence of 'banana' search string, in string variable name

let name = 'apple banana cherry banana mango';
let index = name.lastIndexOf('banana');
console.log(index);

2. find index of last occurrence of 'banana' search string in string variable name searching from from an index of 10 at the trailing end of the string

let name = 'apple banana cherry banana mango';
let start = 10;
let index = name.lastIndexOf('banana', start);
console.log(index);

the last occurrence of the search string 'banana' is ignored because the search happens from a position of 10 from the end

3. find index of last occurrence of 'banama' search string in string variable name

let name = 'apple';
let index = name.lastIndexOf('banana');
console.log(index);

since there is no occurrence of search string in the calling string, lastIndexOf() returns -1


Copyright @2022