Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript
last index
string
communitycreator

What is String.LastIndexOf() method in TypeScript?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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"))
Getting the index position of the last occurence of a string value in a string

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.

RELATED TAGS

typescript
last index
string
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring