substring in Js substr compared to Substring in C

  • 2020-06-07 05:11:53
  • OfStack

Both substring of Js and Substring of C# are used to extract a substring from a string, but they are used in very different ways. Here's a comparison:

The Js substring

Grammar:

The program code
String.substring(start, end)

Description:
Returns a substring from start to end(excluding end).

Example:

The 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

C Substring #

Grammar:

The program code
String.Substring(int startIndex)
String.Substring(int startIndex, int length)

Description:
Returns a substring starting from startIndex to end, or a substring starting from startIndex and of length length.

Example:

The 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 (10)); //error:startIndex cannot be larger than the length of the string.
Response. Write (str Substring (7, 10)); //error: The index and length must refer to the position within the string.

You should have a clear understanding of their use after the above instructions, but there are a few points to be made about THE substring of Js:

start (3,1) is the first parameter, and end (3,1) is the second parameter.
2. When it comes to the returned string is from beginning to end, end value must be greater than the length of the string (that is greater than or equal to the index) of the string, such as the above str. substring (7, 8), according to the index starting from 0 to calculate the maximum end into 7, but with eight side, of course, use is greater than the number of the returned result 8 is also 1 kind, this is interesting;

The js Substr

Grammar:

The program code
stringObject.substr(start,length)

Description:
Extracts a specified number of characters from the start subscript in a string.
start required. The initial index of the substring to be extracted. It has to be a number. If it is negative, the argument declares the position from the end of the string. That is, -1 is the last character in the string, -2 is the second-to-last character, and so on.

length optional. The number of characters in a substring. It has to be a number. If this parameter is omitted, the string from the beginning of stringObject to the end is returned.

Example:

The program code
< script type="text/javascript" > var str="Hello world!" document.write(str.substr(3)) < /script >

Output:
lo world!


Related articles: