Home >Web Front-end >JS Tutorial >The difference and usage between substring and substr in js_javascript skills
Before we start, let’s review the subscripts in js (character subscripts in array elements/strings):
Subscripts always start counting from 0, for example
var arr = [1,2,3];//The length of the array is 3, and the element subscripts are: 0, 1, 2
arr[0] = 1,arr[1]=2..
The string is similar: such as var s = "hello"; //The length of the string is 5, the subscript of the first character 'h' is 0, and so on
String.substring(): used to return a substring of a string
The usage is as follows: string.substring(from, to)
where from refers to the position of the first character of the substring to be removed in the original string
to refers to the last character of the substring to be removed (this parameter does not need to be added)
The following is an example of String.substring() :
1. string.substring(from): This is equivalent to intercepting from the from position to the end of the original string
var s = "hello"; s.substring(1);//就是从下标为1的字符(这里是'e')开始起到字符串末尾全部截取,最终获得子串"ello"
2. string.substring(from, to): Intercept from the position of from to the position of to-1
var s = "hello"; s.substring(1,3);//相当于从位置为1的字符截取到位置为2的字符,得到子串为:"el"
String.substr(): The function is also to extract a substring, but it is different from the above String.substring()
The usage is as follows: string.substr(start, length)
start: refers to the starting subscript of intercepting the substring
length: intercept the length of the substring (can be omitted)
1. string.substr(start, length): First give an example to illustrate:
var s = "hello"; s.substr(1,3);//从下标为1的字符开始截取3个字符长度,最后子串为:ell
Added two special situations:
a. The second parameter exceeds the remaining character length
var s = "hello"; s.substr(1,7)//这种情况下默认从,start位置到原字符串末尾,即返回:"ello"
b. The first parameter is a negative number
In this case, counting from the end of the string, -1 refers to the last character of the string, -2 refers to the penultimate character...and so on
var s = "hello"; s.substr(-3,2)//即从倒数第三个字符开始起截取2个长度,获得:"ll"
2. string.substr(start): does not take the length parameter, and the default refers to intercepting from the start position to the end of the string
var s = "hello"; s.substr(3)//"lo"
The above is a detailed introduction to the difference and usage of substring and substr in js. You can study it in conjunction with previous related articles. I hope it will be helpful to your study.