Difference between substr and substring in javascript, with notes and examples

Lionsure 2020-06-25 Original by the website

Both substring() and substr() are used to extract the specified substring. What is the difference between substr and substring in javascript? First look at their syntax.

 

I. The substring() method

1. Format: stringObject.substring(start [, stop]);

 

2. Description:

1) The two arguments of substring() are start and stop, which means to extract the characters between two specified subscripts in the string.

2) Start is a required argument, and is greater than or equal to 0 and less than the length of stringObject; it is the position of the first character of the substring to be extracted in stringObject.

3) stop is an optional argument, and is greater than or equal to 0 and less than the length of stringObject; if stop is omitted, all characters in stringObject from start to end are extracted.

 

3. Note:

1) substring() includes the character at start, but not the character at stop.

2) If start> stop, the two arguments will be automatically exchanged before extracting the substring.

3) If start = stop, an empty string is returned.

4) If start or stop is smaller than 0, it will be replaced with 0.

 

 

II. The substr() method

1. Format: stringObject.substr(start [, length]);

 

2. Description:

1) The two two arguments of substr() are start and length, which means to extract the substring of the specified length starting from the specified position.

2) Start is a required argument, and is greater than or equal to 0 and less than the length of stringObject; it is the position of the first character of the substring to be extracted in stringObject.

3) length is an optional argument, and is greater than or equal to 0 and less than the length of stringObject minus start; if length is omitted, all characters in stringObject from start to end are extracted.

 

3. Note:

If length is 0 or less than 0, an empty string is returned.

 

 

III. Examples

var str = "abcdefghij";

alert(str.substring(0,3));//Output: abc
       alert(str.substr(0,3));//Output: abc

alert(str.substring(2,6));//Output: cdef
       alert(str.substr(2,6));//Output: cdefgh

alert(str.substring(3));//Output: defghij
       alert(str.substr(3));//Output: defghij