本文翻译自:What is the difference between String.slice and String.substring?
Does anyone know what the difference is between these two methods: 有谁知道这两种方法之间的区别是什么:
String.protorype.slice
String.protorype.substring
#1楼
参考:https://stackoom.com/question/9Pii/String-slice和String-substring有什么区别
#2楼
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
equalsstop
: returns an empty string 如果start
equalsstop
:返回一个空字符串 - 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
, thensubstring
will swap those 2 arguments. 如果start > stop
,那么substring
将交换这两个参数。 - If either argument is negative or is
NaN
, it is treated as if it were0
. 如果任一参数为负数或为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 likesubstr()
in Firefox.