What is the difference between the substr and substring functions?
The substr and substring functions are both methods used for extracting substrings from a string, but they have the following differences:
- The parameters differ: the substr function takes two parameters, the first one being the starting position and the second one being the number of characters to be extracted. On the other hand, the substring function also takes two parameters, with the first one being the starting position and the second one being the end position (excluding the character at the end position).
- Negative numbers are handled differently: when the first parameter of the substr function is a negative number, it indicates counting from the end of the string for the starting position. On the other hand, when the parameter of the substring function is negative, it will automatically be converted to 0.
- If the second parameter in the substr function exceeds the length of the string, it will be trimmed to the end of the string. In contrast, if the second parameter in the substring function exceeds the string length, it will automatically be converted to the string length.
- The return values differ: the substr function returns a substring of a specified length starting from a given position, while the substring function returns a substring from the start position to the end position.
例子:Example
var str = "Hello World!";
console.log(str.substr(0, 5)); // 输出 "Hello"
console.log(str.substring(0, 5)); // 输出 "Hello"
console.log(str.substr(6, 5)); // 输出 "World"
console.log(str.substring(6, 11)); // 输出 "World"
console.log(str.substr(-6)); // 输出 "World!"
console.log(str.substring(-6)); // 输出 "Hello World!"
console.log(str.substr(0, 20)); // 输出 "Hello World!"
console.log(str.substring(0, 20)); // 输出 "Hello World!"
In general, the substr function is more flexible as it can extract a substring by specifying the starting position and the number of characters. On the other hand, the substring function is more intuitive as it can extract a substring by specifying the starting position and the ending position.