The difference between substr and substring in JavaScript

Source: Internet
Author: User

Because there is a need to intercept the string in the project, and then hand the use of the IDE automatically prompts the substr, did not think so many think substr and substring not much difference.

However, it is not, and listen to my one by one way.

1. substr (index, length)

Extracts a specified number of characters from the starting index number in a string.

The substr method can pass in two parameters, index and length. Index is the starting bit and length is the intercept.

When index is a non-negative integer:

A. If you do not pass in a parameter, you get the string itself.

such as: "ABCDEFG". substr (), "ABCDEFG"

B. If only one parameter is passed, that is, index, the last digit of the string is truncated by default.

such as: "ABCDEFG". substr (2), "DEFG".

When index is a negative integer:

C. If a negative integer is passed in the subscript position from the backward forward number, the starting bit is 1, to the negative integer absolute value of the subscript, interception is the former.

such as: "ABCDEFG". substr ( -2), "FG" <=> "ABCDEFG". substr ( -2 + "ABCDEFG". Length)

2. Substring (start, end)

Extracts the character of a string intermediary between two specified subscripts.

Substring is also passed in two parameters, but these two parameters are subscript numbers, the subscript is calculated from 0, the length of the interception is the two inferior

Can be recorded as "with head without tail"

such as: "ABCDEFG". Substring (2,4), "CD"

The difference between substr and substring in JavaScript

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.