The IndexOf () method returns the position of the first occurrence of a specified string value in a string.
The LastIndexOf () method returns the location of the last occurrence of a specified string value, which is searched from behind at the specified position in a string.
Grammar:
IndexOf (): stringobject.indexof (Searchvalue,fromindex)
LastIndexOf (): stringobject.lastindexof (Searchvalue,fromindex)
Parameters |
Description |
Searchvalue |
Necessary. Specifies the string value that needs to be retrieved. |
Fromindex |
IndexOf (): Optional integer parameter. Specifies where to start retrieving in the string. Its legal value is 0 to stringobject.length-1. If this argument is omitted, the search begins at the last character of the string. LastIndexOf (): Optional integer parameter. Specifies where to start retrieving in the string. Its legal value is 0 to stringobject.length-1. If this argument is omitted, the search begins at the last character of the string. |
Description
IndexOf ():
The method will retrieve the string stringobject from beginning to end to see if it contains substring searchvalue. The location at which to begin retrieving is at the fromindex of the string or at the beginning of the string (when no fromindex is specified). If a searchvalue is found, the position of the first occurrence of the Searchvalue is returned. The character position in Stringobject is starting at 0.
LastIndexOf ():
The method retrieves the string stringobject from the end of the head to see if it contains substring searchvalue. The location at which to begin retrieving is at the fromindex of the string or at the end of the string (when no fromindex is specified). If a searchvalue is found, the position of the first character of the Searchvalue in Stringobject is returned. The character position in Stringobject is starting at 0.
return value
LastIndexOf ():
If Searchvalue exists before the fromindex position in Stringobject, the last searchvalue position that appears is returned.
The IndexOf () and LastIndexOf () methods are case-sensitive!
If the string value that you want to retrieve does not appear, the method returns-1.
Instance:
IndexOf ():
1 <Scripttype= "Text/javascript">2 3 4 5 varStr="Hello world!"6 7 document.write (Str.indexof ("Hello") + "<br/>")8 9 document.write (Str.indexof (" World") + "<br/>")Ten One document.write (Str.indexof (" World")) A - - the </Script>
The output of the above code:
0-16
LastIndexOf ():
1 <Scripttype= "Text/javascript">2 3 4 5 varStr="Hello world!"6 7 document.write (Str.lastindexof ("Hello") + "<br/>")8 9 document.write (Str.lastindexof (" World") + "<br/>")Ten One document.write (Str.lastindexof (" World")) A - - the </Script>
The output of the above code:
0-16
This article from: http://www.w3cschool.cn
JavaScript indexOf () method and LastIndexOf () method