find the last index of a character in a string in javascript

You can find the last index of a character in a string in JavaScript using the lastIndexOf() method.

Here's an example of how to find the last index of the letter "o" in the string "hello":

index.tsx
let str = "hello";
let lastIndexOfO = str.lastIndexOf("o");
console.log(lastIndexOfO); // outputs 4
100 chars
4 lines

In this example, the lastIndexOf() method returns the last index at which the character "o" appears in the string "hello", which is 4.

This method also accepts an optional parameter that specifies the starting position of the search. For example, to find the last index of "o" before index 3, you can do:

index.tsx
let lastIndexOfO2 = str.lastIndexOf("o", 3);
console.log(lastIndexOfO2); // outputs 1
86 chars
3 lines

This will start the search from index 3, and return the last index at which the character "o" appears before that position, which is 1 in this case.

gistlibby LogSnag