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

The JavaScript indexOf() method is used when we need to find the position or index number of 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 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 15th index, therefore the first "is" has skipped.

Note - The indexOf() method returns the index of first character of specified value. Otherwise returns -1 in case if specified value does not exists in the specified string.

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

JavaScript Online Test


« Previous Tutorial Next Tutorial »