• JavaScript Video Tutorials

JavaScript String - indexOf() Method



Description

This method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.

Syntax

Use the following syntax to use the indexOf() method.

string.indexOf(searchValue[, fromIndex])

Argument Details

  • searchValue − A string representing the value to search for.

  • fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.

Return Value

Returns the index of the found occurrence, otherwise -1 if not found.

Example

Try the following example.

<html>
   <head>
      <title>JavaScript String indexOf() Method</title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var str1 = new String( "This is string one" );
         var index = str1.indexOf( "string" );
         document.write("indexOf found String :" + index ); 
         
         document.write("<br />");
         var index = str1.indexOf( "one" );
         document.write("indexOf found String :" + index ); 
      </script>  
   </body>
</html>

Output

indexOf found String :8
indexOf found String :15 
javascript_strings_object.htm
Advertisements