top of page

IndexOf() in JavaScript

In JavaScript, indexOf() is a string method that is used to find the location of a substring in a string. Because the indexOf() method is a method of the String object, it must be invoked through a particular instance of the String class. The index position of first character in a string is always starts with zero. If an element is not present in a string, it returns -1.


Note:

  • The indexOf() method returns the first index (position) of a specified value.

  • The indexOf() method returns -1 if the value is not found.

  • The indexOf() method starts at a specified index and searches from left to right.


Syntax:

array.indexOf(item, start)

item: Required.

The value to search for.


start: Optional.

Where to start the search.


Default value is 0.

Negative values start the search from the end of the array.



Example 1:

<!DOCTYPE html>
<html>
<body>

<h2>The indexOf() Method</h2>

<p>IndexOf() returns the position of a specified value in an array:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let index = fruits.indexOf("Apple");

document.getElementById("demo").innerHTML = index;
</script>

</body>
</html>

Output:









Example 2:

<!DOCTYPE html>
<html>
<body>

<h2>The indexOf() Method</h2>

<p>IndexOf() returns the position of a specified value in an array.</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
let index = fruits.indexOf("Apple", 3);

document.getElementById("demo").innerHTML = index;
</script>

</body>
</html>

Output:









The Tech Platform

0 comments
bottom of page