The js string interceptor substr substring slice USES contrast
- 2020-03-30 00:03:37
- OfStack
Three string interceptors are commonly used: substr substring slice, which is called as follows
The most obvious is substr. The second parameter is length, which is the intercept length. The second parameter of the other two functions is the subscript of the end character.
Slice over substring, slice subindex can be negative, such as -1 for the last character, and substring cannot. Substring if start is larger than end, the two arguments are exchanged before the substring is extracted, which slice does not, and slice returns an empty string
Example:
Output:
He
He
He
Helloworl
(empty string)
stringObject.slice(start,end)
stringObject.substr(start,length)
stringObject.substring(start,end)
The most obvious is substr. The second parameter is length, which is the intercept length. The second parameter of the other two functions is the subscript of the end character.
Slice over substring, slice subindex can be negative, such as -1 for the last character, and substring cannot. Substring if start is larger than end, the two arguments are exchanged before the substring is extracted, which slice does not, and slice returns an empty string
Example:
var str="Helloworld"
console.log(str.substr(0, 2))
console.log(str.substring(2, 0))
console.log(str.substring(0, 2))
console.log(str.slice(0, -1))
console.log(str.slice(-1, 0))
Output:
He
He
He
Helloworl
(empty string)