Skip to content

Javascript indexof Method | Search specified item/string in the Array/String

  • by

Javascript indexOf method searches a specified item or string in the Given Array/String and returns its position. Basically, you can find the item or word present in the given string/Array.

For String search, it will return the position of the first occurrence of a specified value in a string.

And For Array item, it will search the array for the specified item and returns its position.

Note: The indexOf() method is case sensitive.

Syntax

// String
string.indexOf(searchvalue, start)
//Array
array.indexOf(item, start)

Parameter Values

  • search value:- Required a search value.
  • start: At which position to start the search. It’s optional and the Default is 0.

Return Value:

It returns the index of the finding string/item where the searchValue is found for the first time. If the searchValue can’t be found in the string then it returns -1.

Examples of javascript substring indexof object

Let see examples of how the indexed() method works with Strings and Array in JS. Let’s see Javascript indexof implementation.

1. Example Javascript string indexof

If finding keyword fount then it will return the position of the first occurrence of a specified value in a string. Otherwise returns -1 if the value not found.

Find the first occurrence of the letter “world” in a string:

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
        	var str = "Hello world, Eyehunts.";
			var n = str.indexOf("world");
        	// show output in alert
        	alert(n)

        </script>
    </head>
    
</html>

Output:

Example Javascript string indexof

2. Example javascript Array indexof

Search an array for the item “Banana”, and search position is default.

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
        	var fruits = ["Banana", "Orange", "Apple", "Mango", "Banana", "Orange", "Apple"];
			var a = fruits.indexOf("Banana");
        	// show ouput in alert
        	alert(a)

        </script>
    </head>
    
</html>

Output:

Do comment if you have any doubts and suggestion on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

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