I have always told others that if you can learn js well, you will not have to worry about it in your life. Now js is more and more widely used, and the influence of js will be further expanded in the future. Recently, a friend asked me how to write the js interception string? What are the differences between the two methods of using substr and substring?
1. Substr method
Returns a substring of the specified length starting at the specified position.
stringvar.substr(start [, length ])
parameter
stringvar
required. A string literal or String object to extract the substring from.
start
required. The starting position of the desired substring. The index of the characters in the string is 0.
length
optional. The number of characters that should be included in the returned substring.
illustrate:
If length is 0 or negative, an empty string is returned. If this parameter is not specified, the substring will continue to stringvar's.
Example:
The following example demonstrates the use of the substr method.
function SubstrDemo(){
var s, ss; // Declare variables.
var s = "The rain in Spain falls mainly in the plain.";
ss = s.substr(12, 5); // Get the substring.
return(ss); // Return "Spain".
}
2. Substring method
Returns the substring at the specified position in the String object.
strVariable.substring(start, end)
"String Literal".substring(start, end)
parameter
start
Indicates the starting position of the substring, the index starts from 0.
end
Indicates the end position of the substring, the index starts from 0.
illustrate
The substring method will return a string containing the substring from start to (excluding end).
The substring method uses the smaller of start and end as the starting point for the substring. For example, strvar.substring(0, 3) and strvar.substring(3, 0) will return the same substring.
If start or end are NaN or negative, replace them with 0.
The length of the substring is equal to the value of the difference between start and end. For example, the length of the substring returned by strvar.substring(0, 3) and strvar.substring(3, 0) is 3.
Example:
The following example demonstrates the use of the substring method.
function SubstringDemo(){
var ss; // Declare the variable.
var s = "The rain in Spain falls mainly in the plain..";
ss = s.substring(12, 17); // Get substring.
return(ss); // Return the substring.
}
Original text: http://www.285868.com/jiaocheng/jpc/show-8538.html