OneBite.Dev - Coding blog in a bite size

find the index of a substring within a string in Javascript

Code snippet on how to find the index of a substring within a string in Javascript

  let str = "Programming is fun!";
  let substringIndex = str.indexOf("fun");

This code sample finds the index of the substring “fun” within the string “Programming is fun!“. The variable str is first assigned to a string of “Programming is fun!“. Then, the indexOf() method is used to query the string for the substring “fun”, and the corresponding index of the substring is saved to the variable substringIndex. In this case, the index of “fun” within the string would be 11.

javascript