两者有什么区别
alert("abc".substr(0,2));
and
alert("abc".substring(0,2));
它们似乎都输出“ab”。
两者有什么区别
alert("abc".substr(0,2));
and
alert("abc".substring(0,2));
它们似乎都输出“ab”。
当前回答
主要的区别在于
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在两者上都能正常工作。
关于这个主题的更多信息可以在这里找到。
正如yatima2975的答案所暗示的,还有一个额外的区别:
Substr()接受一个负的起始位置作为字符串结束的偏移量。Substring()没有。
中数:
如果start为负,substr()将其用作对象的字符索引 字符串结束。
总结一下功能上的差异:
起始偏移量大于等于0的子字符串(begin-offset, end-offset-exclusive)
Substr (begin-offset, length),其中begin-offset也可以为负
区别在于第二个论点。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
差值是第二个参数。它们的第二个参数,虽然都是两个数字,但期望的是两个不同的东西:
当使用子字符串时,第二个参数是不包含的第一个索引:
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'
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开始时,可以使用任何一种方法。