Three string truncation functions are commonly used: substr substring slice. The call method is as follows:
Copy codeThe Code is as follows:
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 truncation length. The second parameter of the other two functions is the subscript of the end character (this does not include the character of this submark, only the first character of the character is truncated)
Compared with substring, slice subscript can be negative. For example,-1 indicates the last character, but substring cannot. If the start value of substring is greater than the end value, the two parameters are exchanged before the substring is extracted. slice does not, and slice returns an empty string.
Example:
Copy codeThe Code is 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
Helloworl
(Null String)