两者有什么区别

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

and

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

它们似乎都输出“ab”。


当前回答

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

其他回答

主要的区别在于

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"        
  

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

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

中数:

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

总结一下功能上的差异:

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

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

子弦(startIndex, endIndex(未包括)

substr(startIndex,多少个字符)

const string = 'JavaScript';

console.log('substring(1,2)', string.substring(1,2)); // a
console.log('substr(1,2)', string.substr(1,2)); // av

差值是第二个参数。它们的第二个参数,虽然都是两个数字,但期望的是两个不同的东西:

当使用子字符串时,第二个参数是不包含的第一个索引:

var s = "string";
s.substring(1, 3); // would return 'tr'

var s = "another example";
s.substring(3, 7); // would return 'ther'

当使用substr时,第二个参数是子字符串中包含的字符数:

var s = "string";
s.substr(1, 3); // would return 'tri'

var s = "another example";
s.substr(3, 7); // would return 'ther ex'

区别在于第二个论点。substring的第二个参数是要停止的索引(但不包括),而substr的第二个参数是要返回的最大长度。

链接?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring