JavaScript IndexOf() Method: Find the Index Of Given Value.

0

In this blog post you’ll learn JavaScript indexOf() Method. Method to find the index of given value from string and array.


Description:

indexOf() method returns the position (index) of first occurrence of a given value from a string.

indexOf() method returns -1 if no value found (case sensitive).


Syntax:

JavaScript


string.indexOf(Searchvalue, start)  

Parameter:

Searchvalue: Value to search. (Required).

start: From which index to start search from. (Optional) The default value is 0.



Example 1: Search for character present in string.

Check the specific character present in the string or not from the string.


JavaScript


    let text = "Hello Welcome to Maketechstuff.com";

    document.write(text.indexOf("e"));
    // Output:
    // 1

As you can see in above code that we get output of 1 when we search for character "e" from the given string. Their is a multiple "e" character present inside string but the indexOf() method returns the index value of 1st occurence of character "e".


Now let's start search from 5th index.


JavaScript


    let text = "Hello Welcome to Maketechstuff.com";

    document.write(text.indexOf("e", 5));
    // Output:
    // 7

As you can see in above code that we tell indexOf() method to start search for character "e" from 5th index of string. And we get the index value 7 as from 5th index the first occurence of  character "e" is on index 7.


Example 2: Search for word present in String.

Search for words present in string.


JavaScript


    let text = "Hello Welcome to Maketechstuff.com";

    document.write(text.indexOf("Welcome"));
    // Output:
    // 6  

The word "Welcome" is present in string and starts from index value 6.


Example 3: Search for array item in Array.

Check presence of specific array item from array using indexOf() method.

You can check the specific array item present in the array or not.


JavaScript


    let fruit_array = ["Mango", "Orange", "Banana", "Apple", "Orange", "Guava", "Mango", "Grapes", "Pomogranate", "Mango"];
    document.write(fruit_array.indexOf("Mango"));
    // Output:
    // 0

As you can see in the above code that item "Mango" occured thrice (at index 0, 6 and 9). We get index 0, If the search start from 0 index of the given array.


If we start search from another index like 2, we get first occurence of item "Mango" that come first from index 2 of given array.


JavaScript


    let fruit_array = ["Mango", "Orange", "Banana", "Apple", "Orange", "Guava", "Mango", "Grapes","Pomogranate", "Mango"];
    document.write(fruit_array.indexOf("Mango", 2));
    // Output:
    // 6
  

The first occurence of item Mango is 6.


So that's how the JavaScript indexOf() method works. If you have any query or suggestion feel free to write in the comment section.


Tags

Post a Comment

0Comments

Share your thoughts.

Post a Comment (0)
To Top