The difference between substr and substring in JS

Source: Internet
Author: User


The role of JS Substring and C # substring is to intercept a substring from a string, but their usage is very different, so let's look at the comparison below:

JS's substring

Grammar:

Program code
String.substring (start, end)

Description
Returns a substring from start to end (not including end).

Demo Sample:

Program code
var str= "ABCDEFGH";
document.write (str.substring (0,1));//return:a
document.write (str.substring (2,5));//RETURN:CDE
document.write (str.substring (7,8));//return:h

substring in C #

Grammar:

Program code
string.substring (int startIndex)
string.substring (int startIndex, int length)

Description
Returns a substring starting from startindex to the end of the string, or a substring that starts at startindex and length.

Demo Sample:

Program code
String str = "ABCDEFGH";
Response.Write (str. Substring (0,1));//return:a
Response.Write (str. Substring (2,3));//RETURN:CDE
Response.Write (str. Substring (7,1));//return:h
Response.Write (str. Substring (7));//return:h
Response.Write (str. Substring);//error:startindex cannot be greater than the string length.
Response.Write (str. Substring (7,10));//error: The index and length must refer to the position within the string.


After the above description of their use should have a clearer understanding of the substring, but there are a few points to JS to explain:

1.start is not necessarily the first parameter, end is not necessarily the second parameter, substring (3,1), start position is 1, the end position is 3;
2. When the substring to be returned is from the start position to the end, the value of end must be greater than or equal to the length of the string, such as the top str.substring (7,8), according to the index from 0 to calculate the end of the maximum value is 7, but this side is 8, of course, It is more interesting to return the same result using a number greater than 8.

The difference between substr and substring in JS

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.