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

To find the last index of a character in a string in TypeScript, we can use the lastIndexOf method available on a given string.

The lastIndexOf method searches the string from right to left, returning the index of the last occurrence of the given character. If the character is not found, it returns -1.

Here's an example:

index.ts
const myString = "hello world";
const charToFind = "o";

const lastIndex = myString.lastIndexOf(charToFind);

console.log(lastIndex); // outputs 7
147 chars
7 lines

In the example above, we create a string myString and define the character we want to find using charToFind.

We then use the lastIndexOf method on myString and pass in charToFind as the argument. The method returns the index of the last occurrence of charToFind in myString.

In this case, the string "o" appears at the 7th index in the string "hello world". The index is zero-based, so the result of lastIndexOf is 7.

It's worth noting that the lastIndexOf method is case-sensitive. To make it case-insensitive, we can convert the string to lower case or upper case using the toLowerCase or toUpperCase method.

gistlibby LogSnag