This post will discuss how to find the last index of a character in a string in JavaScript.

There are several methods to find the last index of a character in a string in JavaScript. Here are some of the most common functions:

1. Using lastIndexOf() function

One way is to use the lastIndexOf() function, which is a built-in function of the string object. This function takes a character or a substring as an argument and returns the index of the last occurrence of that character or substring in the string, or -1 if not found. It searches the string from the end to the beginning and is case sensitive. For example, if we have a string "Hello, world!", we can find the last index of the character "o" using lastIndexOf() like this:

Download  Run Code

 
The lastIndexOf() function can also take a second argument, which is the ending position to search from. This can be useful to find the index of a character before a certain position. For example, to find the last occurrence of "i" in "Mississippi" before position 8:

Download  Run Code

2. Using a for loop

Another way is to use a for loop with the length property and the charAt() function of the string object. This function will loop through the string from the last character to the first one, using an index variable to access each character. Then it will compare each character with the target character and return the index if they are equal, or -1 if not found. For example, using the same string as before, we can find the last index of the character "o" using a for loop like this:

Download  Run Code

 
This function is more verbose and less efficient than using String.lastIndexOf(), but it can be useful to perform some additional operations on each character or provide the ending position to search from.

3. Using exec() function

A third way is to use a regular expression with the RegExp.exec() function. This function will create a regular expression object that matches the target character or substring in the string, using the global flag g to find all occurrences. Then it will use the exec() function to execute the regular expression on the string and return an array of information about each match, or null if not found. The array will contain properties such as index, which is the index of the match in the string. We can use a while loop to iterate over all matches and store the last index in a variable. For example, using the same string as before, we can find the last index of the character "o" using a regular expression like this:

Download  Run Code

4. Using split() and pop() function

Finally, we can use the split() function, which splits a string into an array of substrings, and then using the pop() function, which removes the last element from an array and returns it. For example:

Download  Run Code

That’s all about finding the last index of a character in a string in JavaScript.