Home > Web Front-end > JS Tutorial > body text

javascript indexOf method, lastIndexOf method and substring method_Basic knowledge

WBOY
Release: 2016-05-16 18:55:06
Original
1260 people have browsed it

The indexOf() method returns the first occurrence of a specified string value in a string.
Syntax
stringObject.indexOf(searchvalue,fromindex)
Parameter Description
searchvalue Required. Specifies the string value to be retrieved.
fromindex optional integer parameter. Specifies the position in the string to begin searching. Its legal values ​​are 0 to stringObject.length - 1. If this parameter is omitted, the search will start from the first character of the string.
Explanation
This method will retrieve the string stringObject from beginning to end to see if it contains the substring searchvalue. The starting position of the search is at the fromindex of the string or the beginning of the string (when fromindex is not specified). If a searchvalue is found, the position of the first occurrence of searchvalue is returned. Character positions in stringObject start from 0.
Tips and Notes
Note: The indexOf() method is case sensitive!
Note: If the string value to be retrieved does not appear, this method returns -1.
Example
In this example, we will perform different searches within the "Hello world!" string:


[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]

Output of the above code: The code is as follows:


0
-1
6

lastIndexOf
Method:
Returns the last occurrence position of the substring in the String object.
strObj.lastIndexOf(substring[, startindex]) Parameters

strObj
Required. String object or literal.
substring
Required. The substring to find within the String object.
startindex
Optional. This integer value indicates the index within the String object at which to start the search. If omitted, the search starts at the end of the string.
Description
The lastIndexOf method returns an integer value indicating the starting position of the substring within the String object. If the substring is not found, -1 is returned.
If startindex is negative, startindex is treated as zero. If it is greater than the largest character position index, it is treated as the largest possible index. Perform the search from right to left. Otherwise, this method is the same as indexOf.
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!