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

To find the last index of a substring in a string in TypeScript, you can use the lastIndexOf() method of the string. The lastIndexOf() method returns the index of the last occurrence of the specified substring in the string. If the substring is not found in the string, it returns -1.

Here is an example code snippet that demonstrates the usage of lastIndexOf() method:

index.ts
const str = "Hello World";
const substr = "o";
const lastIndex = str.lastIndexOf(substr);
console.log(lastIndex); // Output: 7
127 chars
5 lines

In the above code, we have a string "Hello World" and a substring "o". We are using the lastIndexOf() method to find the last index of the substring "o" in the string. The lastIndex variable will contain the value 7, which is the last index of "o" in the string.

Note that the lastIndexOf() method is case-sensitive. If you need a case-insensitive search, you can convert both the string and substring to lowercase or uppercase using toLowerCase() or toUpperCase() method before using lastIndexOf() method.

gistlibby LogSnag