JavaScript indexOf method entry example (calculates the first occurrence of a specified character in a string)

  • 2020-03-30 04:09:10
  • OfStack

JavaScript method indexOf

The indexOf method calculates the first occurrence of a specified string in a string and returns the value. The syntax is as follows:


str_object.indexOf( search, start )

Parameter description:

parameter instructions
str_object String (object) to manipulate
search A necessity. The string to retrieve
start Optional. Specifies where to start the retrieval, and if the parameter is omitted, the retrieval begins with the first character of the string

Tip: strings are counted from 0.

Example of the indexOf method


<script language="JavaScript"> var str = "www.jb51.net";
document.write( str.indexOf( "." ) ); </script>

Run the example and output:


3

IndexOf is case-sensitive and returns -1 if the string value to be retrieved does not appear.


Related articles: