There are three commonly used string interception functions: substr substring slice. The calling method is as follows:
Copy the code code as follows:
stringObject.slice(start,end)
stringObject.substr(start,length)
stringObject.substring(start,end)
The most obvious one is substr. The second parameter is length, which is the interception length. The second parameters of the other two functions are the subscript of the last character (the character of the subscript is not included here, only the first character of the character is intercepted. one character)
Compared with slice, substring, slice subscript can be a negative number, such as -1 represents the last character, but substring cannot. If substring start is larger than end, then these two parameters will be exchanged before extracting the substring, but slice will not and slice will return an empty string.
example:
Copy the code code as follows:
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
Helloworld
(empty string)