Skip to content

JavaSript string indexof method | finds string and index

  • by

The JavaSript string indexof method returns the position of specified (search) value in a string. It returns the index value of the first occurrence search string.

Note: The indexOf() method is case sensitive.

Syntax

string.indexOf(searchvalue, start)

Parameter Values

  • searchvalue:- A Search value. (Required)
  • start:- At which position to start the search. It’s optional and Default values is 0.

Return value

It returns the index of the first occurrence of the search string. And returns -1 if the string is not found.

Examples of JavaSript string indexof method

Let’s see the example of how to find the specified string index value in JS.

1. Find without position(start)

Find the first occurrence of the letter (char) ” T ” in a string: And print the output value in Alert box.

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
        	var str = "Hello world, welcome to EyeHunt Tutorail.";
			var n = str.indexOf("e");

        	// show output in alert
        	alert(n)

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

Output:

2. Using Start in indexof()

Find the first occurrence of the string “B” in a given string, starting the search at position 3:

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
        	var str = "A B C A B C A B C D";
			var n = str.indexOf("B", 3);

        	// show output in alert
        	alert(n)

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

Output:

JavaSript string indexof method

Do comment if you have any examples, 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading