Home >Web Front-end >Front-end Q&A >How to use javascript substr() method
In JavaScript, the substr() method is used to intercept a substring of a specified length from a specified index position. It contains two parameters. The first parameter indicates the starting subscript of the substring to be intercepted. The second parameter represents the intercepted length, the syntax is "string.substr(start,length)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
substr() is used to intercept a substring of specified length from the specified index position.
The substr() method can intercept substrings according to the specified length. It contains two parameters, the first parameter indicates the starting subscript of the substring to be intercepted, and the second parameter indicates the length of the interception.
Syntax format:
string.substr(start,length)
start: required. The starting index of the substring to be extracted. Must be a numeric value. If negative, this parameter declares the position from the end of the string. That is, -1 represents the last character, -2 represents the penultimate character, and so on. This is useful when the left character length is not fixed.
length: Optional. The number of characters in the substring. Must be a numeric value. If this parameter is omitted, the string from the beginning to the end of string is returned.
Return value:
A new string containing the length starting from the start of string (including the character pointed to by start) characters. If length is not specified, the returned string contains characters from start to the end of string.
Example:
Get the subscript position of the last period of the string, and then intercept 4 characters starting from the subsequent position.
var s = "hello world!欢迎来到PHP中文网!//m.sbmmt.com/course/list/29.html"; var b = s.substr(s.lastIndexOf(".") + 1,4); //截取最后一个点号后4个字符 console.log(b); //返回子字符串“html”
If the second parameter is omitted, it means that all characters from the starting position to the end are intercepted. Considering that the length of the extension is not fixed, omitting the second parameter will be more flexible.
var b = s.substr(s.lastIndexOf(".") + 1);
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to use javascript substr() method. For more information, please follow other related articles on the PHP Chinese website!