menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:lastIndexOf() method

menu

The lastIndexOf() method in JavaScript is similar to the indexOf() method, but it searches for the last occurrence of a specified value within a string and returns its index. If the value is not found, it returns -1. Here's a deep dive into the lastIndexOf() method in JavaScript:

Syntax:

javascriptstring.lastIndexOf(searchValue);
string.lastIndexOf(searchValue, fromIndex);
  • string: The string in which you want to search for the searchValue.

  • searchValue: The value you want to find within the string.

  • fromIndex (optional): The index at which the search starts, counting from the end of the string. If omitted, the search starts from the end of the string.

Basic Example:

javascriptstring.lastIndexOf(searchValue);
string.lastIndexOf(searchValue, fromIndex);

In this example, the lastIndexOf() method searches for the last occurrence of the substring "Hello" within the text string and returns the index 13, indicating the position of the last "Hello" in the string.

Search for Substrings:

The lastIndexOf() method can search for substrings within a string:

javascriptconst text = "Hello, World! Hello, Universe!";
const lastIndexOfHello = text.lastIndexOf("Hello");
console.log(lastIndexOfHello); // 13

Here, it finds the substring "World" within the text string and returns the starting index of 7.

Search from a Specified Index:

You can specify the fromIndex parameter to start the search from a particular index, counting from the end of the string:

javascriptconst text = "Hello, World!";
const lastIndexOfWorld = text.lastIndexOf("World");
console.log(lastIndexOfWorld); // 7

In this case, the search for "Hello" starts from index 18 (counting from the end of the string), and it finds the first occurrence of "Hello" at index 0.

Handling Not Found:

If the searchValue is not found within the string, the lastIndexOf() method returns -1:

javascriptconst text = "Hello, World!";
const lastIndexOfZ = text.lastIndexOf("Z");
console.log(lastIndexOfZ); // -1

Case-Sensitive Search:

By default, lastIndexOf() performs a case-sensitive search. This means that it distinguishes between uppercase and lowercase characters. To perform a case-insensitive search, you can use the toLowerCase() method to convert the string to lowercase and then search for the value.

Use Cases:

  • Searching for the last occurrence of a specific value or substring within a string.

  • Validating the presence of a keyword or term within text.

  • Determining the position of the last character or substring within a larger string.

The lastIndexOf() method is a valuable tool for string manipulation and searching within strings in JavaScript. It's commonly used in various scenarios, such as text processing, validation, and parsing.

1280 x 720 px