What is String.LastIndexOf() method in TypeScript?

Overview

We can use the String.LastIndexOf() method to get the index position of the last time a particular string value appears in the given string. This method searches a string from end to beginning.

Syntax

string.lastIndexOf(substring)
Syntax for lastIndex() method in TypeScript

Parameters

substring: This is the value, string value, or substring for which we want to get the index position of its last occurrence in a string.

Return value

The value returned is an integer that represents the index position of the last occurrence of a specified substring in a string. If the value is not found, then a -1 is returned. It is case-sensitive.

Code example

Let's look at the code below:

export {}
// create some strings
let greeting:string = "Welcome to Edpresso"
let proverb:string = "If a child washed his hands, he could eat with kings"
let author:string = "Chinua Achebe"
let book:string = "Things fall apart"
// get index position of last occurence of some string values
console.log(greeting.lastIndexOf("to"))
console.log(proverb.lastIndexOf("M"))
console.log(author.lastIndexOf("e"))
console.log(book.lastIndexOf("fall"))

Explanation

In the code above:

  • Line 1: We export our code as a module.
  • Lines 4 to 7: We create some strings.
  • Lines 10 to 13: We use the lastIndexOf() method to get the last occurrence of a string value in a string and log it to the console.

Free Resources