Use and comparison of the js string truncation function substr substring slice

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.