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

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

Parameter Values

  • search value:- Required a search value.
  • start: At which position to start the search. It’s optional and 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:

Output:

Example Javascript string indexof

2. Example javascript Array indexof

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

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.