OneBite.Dev - Coding blog in a bite size

find the last occurrence of a character in a string in Javascript

Code snippet on how to find the last occurrence of a character in a string in Javascript

function lastIndexOf(str, character) {
  let lastIndex = -1;
  for (let index = 0; index < str.length; index++) {
    if (str[index] === character) {
      lastIndex = index;
    }
  }
  return lastIndex; 
}

This code finds the last occurrence of a character in a string using Javascript. Firstly, the function creates a variable “lastIndex” with a default value of -1 which is used to store the last index of the character string. Next, it runs a for loop which goes through each character of the string. Inside the loop, we use an if condition to check if the current character is equal to the character we want to find. If the condition is true, we set the “lastIndex” variable to the current index. If the condition is false, it just keeps looping until it finds a match or reaches the end of the string. Lastly, it returns the “lastIndex” variable which contains the last index of the character string.

javascript