Differences between substr and substring in Javascript _ javascript tips-js tutorial

Source: Internet
Author: User
This article mainly introduces the difference between substr and substring in Javascript, which is very simple and clear. If you need it, you can take a closer look. Because there is a need to intercept the string in the project, and then use the substr automatically prompted by IDE, I didn't think that there is much difference between substr and substring.

However, this is not the case. Let me hear it one by one.

1. substr (index, length)

Extracts a specified number of characters from the start index number.

The substr method can be used to input two parameters: index and length. Index is the start position and length is the truncation length.

When index is a non-negative integer:

A. If no parameter is input, the result is the string itself.

For example, "abcdefg". substr ()-> "abcdefg"

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

For example, "abcdefg". substr (2)-> "defg ".

When index is a negative integer:

C. If you input a negative integer subscript bit, it will start from the back to the front and start from 1 to reach the subscript bit of the negative integer absolute value, and the truncation will be from the back to the back.

For example, "abcdefg". substr (-2)-> "fg" <=> "abcdefg". substr (-2 + "abcdefg". length)

2. substring (start, end)

Extract the characters that the string contains between two specified subscripts.

Substring is also passed in two parameters, but both parameters are subscript numbers. The subscript starts from 0 and the truncation length is the difference between the two

It can be recorded as "headers without tails"

For example, "abcdefg". substring (2, 4)-> "cd"

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.