Home >Web Front-end >JS Tutorial >What are the differences between substring, slice and substr in js?
The differences between substring, slice and substr in js are: 1. slice and substring receive the starting position and end position, while substr receives the starting position and the length of the string to be returned; 2. , slice adds the length of the string to the corresponding negative number, and the result is used as a parameter.
The differences between substring, slice and substr in js are:
slice()
method returns selected elements from an existing array.
string.slice(start, end)
Extract a string
string.substring(start , end)
Extract a string, end does not support negative numbers
string.substr(start, len)
Extract a string with a length of len
1. slice and substring receive the starting position and end position (excluding the end position), while substr receives the starting position and the length of the string to be returned. Look directly at the following example:
var test = 'hello world'; alert(test.slice(4,7)); //o w alert(test.substring(4,7)); //o w alert(test.substr(4,7)); //o world
2. Substring uses the smaller of the two parameters as the starting position and the larger parameter as the ending position. For example:
alert(test.substring(7,4)); //o w
3. When the received parameter is a negative number, slice will add the length of its string to the corresponding negative number, and the result will be used as the parameter; substr will only add the first parameter to the string. The result of adding the lengths is used as the first parameter; substring simply converts all negative parameters directly to 0. The test code is as follows:
var test = 'hello world'; alert(test.slice(-3)); //rld alert(test.substring(-3)); //hello world alert(test.substr(-3)); //rld alert(test.slice(3,-4)); //lo w alert(test.substring(3,-4)); //hel alert(test.substr(3,-4)); //空字符串
Related learning recommendations: javascript video tutorial
The above is the detailed content of What are the differences between substring, slice and substr in js?. For more information, please follow other related articles on the PHP Chinese website!