1 The difference between the three
substr(start,length)
length
Returns the length starting from the specified subscript字符
, which can be negativesubstring(start,end)
Returns between the specified subscripts字符
, including start, excluding endslice(start,end)
Returns between the specified subscripts数组元素
, including start, excluding endsubstr
andsubstring
are string-specific methods,slice
both array methods and string methods
2 substring和slice
2.1 substring MDN
2.2 slice MDN
2.3 Differences
substring
The main difference between and slice
is that substring
if any parameter is less than 0 or Nan, it will be treated as 0. slice
If the parameter is negative, it represents the penultimate element in the original array.
3. Take a chestnut
var stringValue = "hello world";
console.log(stringValue.slice(3)); //”lo world”
console.log(stringValue.substring(3)); //”lo world”
console.log(stringValue.substr(3)); //”lo world”
console.log(stringValue.slice(3,7)); //”lo w”
console.log(stringValue.substring(3,7)); //”lo w”
console.log(stringValue.substr(3,7)); //”lo worl”
console.log(stringValue.slice(-3)); //"rld" 从后往前数3个开始
console.log(stringValue.substring(-3)); //"hello world" 为负,默认从0开始
console.log(stringValue.substr(-3)); //"rld"
console.log(stringValue.slice(3,-4)); //”lo w” 下标从3开始到-4(从后往前数4个)
console.log(stringValue.substring(3,-4)); //”hel”
console.log(stringValue.substr(3,-4)); //”” 长度为负,默认不显示