The IndexOf () method returns the location of the first occurrence of a specified string value in a string.
Grammar
Stringobject.indexof (Searchvalue,fromindex)
Parameter description
Searchvalue required. A string value that requires retrieval.
Fromindex an optional integer parameter. Specify where to start retrieving in the string. Its legal value is 0 to stringobject.length-1. If this argument is omitted, it is retrieved from the first character of the string.
Description
This method retrieves the string stringobject from beginning to end to see if it contains substring searchvalue. The location at which to start retrieving is at the fromindex of the string or at the beginning of the string (no fromindex is specified). If a searchvalue is found, it returns the position of the first occurrence of searchvalue. The character position in the Stringobject is starting at 0.
Tips and comments
Comments:
indexOf ()method is sensitive to case sensitivity!
Note: If the string value to retrieve does not appear, the method returns-1.
Instance
In this case, we'll do a different search within the "Hello world!" string:
<script type= "Text/javascript" > var str= "Hello world!" document.write (Str.indexof ("Hello") + "") document.write (Str.indexof ("World") + "") document.write (Str.indexof (" World)) </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
The output of the above code:
Copy Code code as follows:
LastIndexOfMethod:
Returns the last occurrence of the substring of a string object.
Strobj.lastindexof (substring[, startindex])
Parameters
Strobj
Required option. A String object or text.
Substring
Required option. The substring to find within the string object.
startindex
Options available. The integer value indicates the starting index position of the lookup within the String object. If omitted, the lookup starts at the end of the string.
Description
The LastIndexOf method returns an integer value that indicates the starting position of the substring of the string object. If no substring is found, returns-1.
If the startindex is a negative number, the startindex is treated as zero. If it is larger than the maximum character position index, it is considered to be the largest possible index.
Performs a lookup from right to left. Otherwise, the method is the same as indexOf.