两者有什么区别

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

and

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

它们似乎都输出“ab”。


当前回答

substr (MDN)的参数为(from, length)。 substring (MDN)的参数为(from, to)。

更新:MDN考虑substr遗留问题。

alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"

你可以记住substring(带i)接受索引,就像另一个字符串提取方法slice(带i)一样。

当从0开始时,可以使用任何一种方法。

其他回答

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

区别在于第二个论点。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

主要的区别在于

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"        
  

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

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

子弦(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