JavaScript indexOf(): Find the Position of a Specified Value in a String

The JavaScript indexOf() method is used when we need to find the position or index number of a specified value (or substring) in a string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "JavaScript is Fun. Is not it?";
      let myPosition = myString.indexOf("Fun");
      
      document.getElementById("xyz").innerHTML = myPosition;
   </script>
   
</body>
</html>
Output

Since indexing starts with 0, therefore, in the string "JavaScript is Fun. Is not it?"

Similarly, the first character of "Fun", that is, 'F' is at index no. 14, therefore the output of the above program is 14.

JavaScript indexOf() syntax

The syntax of the indexOf() method in JavaScript is:

string.indexOf(subString, startIndex)

The startIndex parameter is optional. Its default value is 0. This parameter is used when we need to start searching for specified subString from any particular startIndex value. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>

   <script>
      let x = "JavaScript is fun, is not it?";
      let y = x.indexOf("is", 15);
      
      document.getElementById("abc").innerHTML = y;
   </script>
   
</body>
</html>
Output

Since the searching for "is" starts from the 15th index, the first "is" has been skipped.

Note: The indexOf() method returns the index of the first character of the specified value. Otherwise, it returns -1 if the specified value does not exist in the specified string.

Note: There is another method available in JavaScript that can be used to find the position of a substring in a given string, which is search(). But there is a little difference between these two, which is described in a separate post. For further information, you can refer to indexOf vs. search().

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!