Example of getting started with the JavaScript indexOf method (calculate the position where the specified character first appears in the string), javascriptindexof
JavaScript indexOf Method
The indexOf method is used to calculate the position where a specified string first appears in a string and return this value. The syntax is as follows:
Copy codeThe Code is as follows:
Str_object.indexOf (search, start)
Parameter description:
Parameters |
Description |
Str_object |
String (object) to be operated) |
Search |
Required. String to be retrieved |
Start |
Optional. Specifies the start position of the search. If this parameter is omitted, the search starts from the first character of the string. |
Tip: the string is counted from 0.
IndexOf Method Instance
Copy codeThe Code is as follows:
<Script language = "JavaScript">
Var str = "www.jb51.net ";
Document. write (str. indexOf ("."));
</Script>
Run this example and output:
Copy codeThe Code is as follows:
3
IndexOf is case sensitive. If the string value to be retrieved does not appear,-1 is returned.
Use the indexOf () method of the string object to locate the first occurrence location of a specified character in the string
Int location = "abcdefg". IndexOf ("d ");
C #, the value of location after execution is 4
How to Use the indexOf function in javascript
JavaScript indexOf () method
Definition and usage
The indexOf () method returns the position of the first occurrence of a specified string value.
Syntax
StringObject. indexOf (searchvalue, fromindex)
Parameter description
Searchvalue: required. Specifies the string value to be retrieved.
Fromindex: an optional integer. Specifies the position where the search starts in the string. The valid value is 0 to stringObject. length-1. If this parameter is omitted, It is retrieved from the first character of the string.
Method description
This method retrieves the stringObject string from start to end to see if it contains the searchvalue. The start position is at the string's fromindex or the start of the string (when fromindex is not specified ). If a searchvalue is found, the first position of the searchvalue is returned. The character position in stringObject starts from 0.
Tips and comments
Note: The indexOf () method is case sensitive!
Note: If the string value to be retrieved does not appear, this method returns-1.
Instance
In this example, we will! "Different searches within the string:
<Script type = "text/javascript">
Var str = "Hello world! "
Document. write (str. indexOf ("Hello") + "<br/> ")
Document. write (str. indexOf ("World") + "<br/> ")
Document. write (str. indexOf ("world "))
</Script>
Output of the above Code:
0
-1
6