JS substr and substring

Source: Internet
Author: User
Tags truncated

I don't know why, every time I need to use a function that intercepts a string, I always tell the difference between substr and substring . But then again, these two really look alike. Why does JS have these two so "seemingly" things?

SUBSTR (start, [length])

Intercepts a string of length from the specified subscript start.

If start is negative, the count starts at the end of the string, such as 1, which starts at the bottom of the countdown. If the absolute value of this negative number is greater than the string length, then it is considered to be 0.

If length is 0 or negative, an empty string is returned, and if length is omitted, it is truncated from start to end.

SUBSTRING (start, [stop])

Intercepts a string from the subscript start to the stop (character that does not include the stop position).

If stop is omitted, the end is truncated. Start and stop must be non-negative integers, that is, 0,1,2 ...

If start is greater than Stop,js, they are automatically swapped and then calculated.

If Start equals stop, an empty string is returned.

The basic rule is this, this is the grammatical category of things, very thin and cumbersome, but also bad distinction. The scenario in which you actually use SUBSTR may be the following.

    • Take the first few words of a large paragraph of text to form a thumbnail message.
    • Get the first and the end of private information such as ID cards, bank cards, phone numbers, and then assemble and then publicly display.

Substring may be like this:

    • Gets the last paragraph of the URI
    • Get email address @ The following paragraph

They are often used with indexOf.

For more details, refer to MDN

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring

JS substr and substring

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.