Talking about the usage difference of substr(), substring() and slice()

1 The difference between the three

  • substr(start,length)lengthReturns the length starting from the specified subscript 字符, which can be negative
  • substring(start,end)Returns between the specified subscripts 字符, including start, excluding end
  • slice(start,end)Returns between the specified subscripts 数组元素, including start, excluding end
  • substrand substringare string-specific methods, sliceboth array methods and string methods

2 substring和slice

2.1 substring MDN

insert image description here

2.2 slice MDN

insert image description here

2.3 Differences

substringThe main difference between and sliceis that substringif any parameter is less than 0 or Nan, it will be treated as 0. sliceIf 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));      //”” 长度为负,默认不显示

Guess you like

Origin blog.csdn.net/Dax1_/article/details/125252032