What is the difference between substr and substring?

What is the difference between

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

and

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

They both seem to output “ab”.


The difference is in the second argument. The second argument to substring is the index to stop at (but not include), but the second argument to substr is the maximum length to return.

Links?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring


substr (MDN) takes parameters as (from, length) .
substring (MDN) takes parameters as (from, to) .

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

You can remember substring takes indices, as does yet another string extraction method, slice.

When starting from 0 you can use either method.


As hinted at in yatima2975's answer, there is an additional difference:

substr() accepts a negative starting position as an offset from the end of the string. substring() does not.

From MDN:

If start is negative, substr() uses it as a character index from the end of the string.

So to sum up the functional differences:

substring(begin-offset, end-offset-exclusive) where begin-offset is 0 or greater

substr(begin-offset, length) where begin-offset may also be negative

链接地址: http://www.djcxy.com/p/70656.html

上一篇: 用于查找长度为k的第一个重复子串的算法

下一篇: substr和substring有什么区别?