/

HTML / CSS / JavaScript Tutorial

JavaScript String method: indexOf()

[this page | pdf | back links]

The indexOf() method (when applied to a JavaScript string) returns the position of the first occurrence of a specified string in the string. It is case-sensitive. It returns -1 if the string being searched for is not found.

 

It has the following syntax with the following parameters:

 

string.indexOf(searchstring, start)

 

Parameter

Required / Optional

Description

searchstring

Required

String to be searched for

start

Optional

(Default is 0). Position at which to start search

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
var str1 = "ababab", str2 = "ab";
document.getElementById("Example").innerHTML =
  'var str1 = "' + str1 + '";<br>' +
  'var x = str1.indexOf("' + str2 + '", 1);';
document.getElementById("Result").innerHTML
  = str1.indexOf(str2, 1);
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodStringIndexOf() {
  var z = "abc"; return !!z.indexOf;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript String Variables


Desktop view | Switch to Mobile