OneBite.Dev - Coding blog in a bite size

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

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

 function findFirstOccurrence(str, char) {
  for (let i = 0; i < str.length; i++) {
    if (str[i] == char) {
      return i;
    }
  }
  return -1;
}

This code takes a string and a character as parameters, and finds the first occurrence of the character in the string. It does this by looping through each character of the string until it finds an exact match with the character that was passed as a parameter. If there is a match, it returns the index of the character from the string. If there is no match, it returns -1.

javascript