Home >>JavaScript String Methods >JavaScript String indexOf() Method

JavaScript String indexOf() Method

What is JavaScript String indexOf() Method

JavaScript indexOf() method is used to find the position of the first occurrence of some specified value in a given input string. It returns -1 value if the value to search for never occurs in the given input string.

Syntax:

string.indexOf(searchvalue, start)

Parameter Values

Parameter Description
searchvalue This is a required parameter. It defines the string to search for.
start This is an optional parameter. It defines at which position to start the search.

Browser Support

Method Chrome Edge Firefox Safari Opera
indexOf() Yes Yes Yes Yes Yes

Here is an example of indexOf() method:

<html>
<body>
<p>Click the button to see the Output</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
  var str = "Welcome to PHPTPOINT";
  var n = str.indexOf("PHP");
  document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
Output:

Click the button to see the Output

 

Example 2:

 

<html>
<body>
<p>Click the button to see the Output</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
  var str = "Welcome to PHPTPOINT";
  var n = str.indexOf("T");
  document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
Output:

Click the button to see the Output

 


No Sidebar ads