slice()
works like substring()
with a few different behaviors.
(slice()
工作方式类似于substring()
,但有一些不同的行为。)
Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);
What they have in common:
(他们有什么共同点:)
- If
start
equals stop
: returns an empty string(如果start
equals stop
:返回一个空字符串)
- If
stop
is omitted: extracts characters to the end of the string(如果省略stop
:将字符提取到字符串的末尾)
- If either argument is greater than the string's length, the string's length will be used instead.
(如果任一参数大于字符串的长度,则将使用字符串的长度。)
Distinctions of substring()
:
(substring()
区别 :)
- If
start > stop
, then substring
will swap those 2 arguments.(如果start > stop
,那么substring
将交换这两个参数。)
- If either argument is negative or is
NaN
, it is treated as if it were 0
.(如果任一参数为负数或为NaN
,则将其视为0
。)
Distinctions of slice()
:
(slice()
区别 :)
- If
start > stop
, slice()
will return the empty string.(如果start > stop
, slice()
将返回空字符串。)
( ""
)(( ""
))
- If
start
is negative: sets char from the end of string, exactly like substr()
in Firefox.(如果start
为负数:从字符串末尾设置char,与Firefox中的substr()
完全相同。)
This behavior is observed in both Firefox and IE.(在Firefox和IE中都观察到此行为。)
- If
stop
is negative: sets stop to: string.length – Math.abs(stop)
(original value), except bounded at 0 (thus, Math.max(0, string.length + stop)
) as covered in the ECMA specification .(如果stop
为负:将stop设置为: string.length – Math.abs(stop)
(原始值),除了以0为界(因此, Math.max(0, string.length + stop)
),如ECMA规范中所述 。)
Source: Rudimentary Art of Programming & Development: Javascript: substr() vs substring()
(来源: 编程与开发的基础艺术:Javascript:substr()vs substring())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…