两者有什么区别

alert("abc".substr(0,2));

and

alert("abc".substring(0,2));

它们似乎都输出“ab”。


当前回答

正如yatima2975的答案所暗示的,还有一个额外的区别:

Substr()接受一个负的起始位置作为字符串结束的偏移量。Substring()没有。

中数:

如果start为负,substr()将其用作对象的字符索引 字符串结束。

总结一下功能上的差异:

起始偏移量大于等于0的子字符串(begin-offset, end-offset-exclusive)

Substr (begin-offset, length),其中begin-offset也可以为负

其他回答

我最近遇到的另一个问题是,在IE 8中,“abcd”.substr(-1)错误地返回“abcd”,而Firefox 3.6则返回“d”。Slice在两者上都能正常工作。

关于这个主题的更多信息可以在这里找到。

主要的区别在于

Substr()允许您指定要返回的最大长度 substring()允许你指定索引,第二个参数不包括在内

substr()和substring()之间还有一些额外的微妙之处,比如相等参数和负参数的处理。还要注意substring()和slice()是相似的,但并不总是相同的。

  //*** length vs indices:
    "string".substring(2,4);  // "ri"   (start, end) indices / second value is NOT inclusive
    "string".substr(2,4);     // "ring" (start, length) length is the maximum length to return
    "string".slice(2,4);      // "ri"   (start, end) indices / second value is NOT inclusive

  //*** watch out for substring swap:
    "string".substring(3,2);  // "r"    (swaps the larger and the smaller number)
    "string".substr(3,2);     // "in"
    "string".slice(3,2);      // ""     (just returns "")

  //*** negative second argument:
    "string".substring(2,-4); // "st"   (converts negative numbers to 0, then swaps first and second position)
    "string".substr(2,-4);    // ""
    "string".slice(2,-4);     // ""

  //*** negative first argument:
    "string".substring(-3);   // "string"        
    "string".substr(-3);      // "ing"  (read from end of string)
    "string".slice(-3);       // "ing"        
  
let str = "Hello World"

console.log(str.substring(1, 3))  // el -> Excludes the last index
console.log(str.substr(1, 3))  // ell -> Includes the last index

正如yatima2975的答案所暗示的,还有一个额外的区别:

Substr()接受一个负的起始位置作为字符串结束的偏移量。Substring()没有。

中数:

如果start为负,substr()将其用作对象的字符索引 字符串结束。

总结一下功能上的差异:

起始偏移量大于等于0的子字符串(begin-offset, end-offset-exclusive)

Substr (begin-offset, length),其中begin-offset也可以为负

最大的区别是,substr()是一个仍然可以使用的已弃用方法,但应该谨慎使用,因为它们预计在未来的某个时候将被完全删除。您应该努力从代码中删除它们的使用。substring()方法成功并指定了前者。