This article mainly introduces the difference between substr and substring in Javascript, which is very simple and clear. If you need it, you can take a closer look. Because there is a need to intercept the string in the project, and then use the substr automatically prompted by IDE, I didn't think that there is much difference between substr and substring.
However, this is not the case. Let me hear it one by one.
1. substr (index, length)
Extracts a specified number of characters from the start index number.
The substr method can be used to input two parameters: index and length. Index is the start position and length is the truncation length.
When index is a non-negative integer:
A. If no parameter is input, the result is the string itself.
For example, "abcdefg". substr ()-> "abcdefg"
B. If only one parameter is input, that is, index, it is truncated to the last digit of the string by default.
For example, "abcdefg". substr (2)-> "defg ".
When index is a negative integer:
C. If you input a negative integer subscript bit, it will start from the back to the front and start from 1 to reach the subscript bit of the negative integer absolute value, and the truncation will be from the back to the back.
For example, "abcdefg". substr (-2)-> "fg" <=> "abcdefg". substr (-2 + "abcdefg". length)
2. substring (start, end)
Extract the characters that the string contains between two specified subscripts.
Substring is also passed in two parameters, but both parameters are subscript numbers. The subscript starts from 0 and the truncation length is the difference between the two
It can be recorded as "headers without tails"
For example, "abcdefg". substring (2, 4)-> "cd"