String indexOf() method in JavaScript

You can use the indexOf() method in JavaScript to find index i.e position of the first appearance for the specified string. If the specified string is not found in the main string then it returns -1.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>indexOf</title>
  <script>
    var str = "Try to find me here. If you failed find me at other places.";
    var index1 = str.indexOf("find");
    document.write('position of find is: ', index1);
    document.write("<br />");
    var index2 = str.indexOf("search");
    document.write('position of search is: ', index2);
  </script>
</head>
<body>
</body>
</html>

Output:

position of find is: 7
position of search is: -1

**Note:

indexOf() methods returns -1 if specified string is not found.

Second parameter for indexOf() method:

indexOf() method in JavaScript can take the second parameter by which you can give a starting position for the search.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>indexOf()</title>
  <script>
    var str = "Try to find me here. If you failed find me at other places.";
    var index1 = str.indexOf("find", 20);
    document.write('position of find using indexOf is: ', index1);
  </script>
</head>
<body>
</body>
</html>

Output:

position of find using indexOf is: 35

**Note:

JavaScript starts counting positions from zero. Therefore, counting will take place like 0,1,2,3,…

Additional Links:

String lastIndexOf() method in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *