OneBite.Dev - Coding blog in a bite size

find the position of the first occurrence of a substring in a string in Javascript

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

  function findFirstSubstring(string, substr) {
    return string.indexOf(substr);
  }

This code uses the indexOf() method in JavaScript to find the position of the first occurrence of a substring in a string. It is a function that takes two parameters - a string, and a substring to be searched for in the string. The output of this method is the position of the first occurrence of the substring in the string. If the substring is not found in the string, it returns the value -1. So, if the returned value of the function is equal to -1, it means that the substring was not found in the string. Otherwise, the position of the first occurrence is returned. To use this function, simply pass the two parameters - the string to search, and the substring to search for - and store the returned value into a variable.

javascript