String Methods: indexOf

String methods help you to work with strings. One way is to find a string in a string, using the indexOf() method, which returns the index of (the position of) the first occurrence of a specified text in a string. In this example, we are looking for the first occurence of the text string locate:

HTML file: Displayed by browser:
<body>
<p id="p1">Please locate where 'locate' occurs!.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    var str = document.getElementById("p1").innerHTML;
    var pos = str.indexOf("locate");
    document.getElementById("demo").innerHTML = pos;
}
</script>
</body>

Please locate where 'locate' occurs!.

Remember, this is 0-based counting, so JavaScript starts with 0. To follow along with how this function does its counting, here's a complete breakdown: #0 (P) = no match; #1 (l) = no match; #2 (e) = no match; #3 (a) = no match; #4 (s) = no match; #5 (e) = no match; #6 ( ) = no match; #7 (l) = maybe match; #8 (o) = maybe match; #9 (c) = maybe match; #10 (a) = maybe match; #11 (t) = maybe match; #12 (e) = It's a match, return the position of the first maybe match (7). Note: If the function cannot find the string, it will return a value of -1.

A second parameter is acceptable as the starting position for the search.

BackTable of ContentsNext