String.slice和String.substring有什么区别? [英] What is the difference between String.slice and String.substring?
本文介绍了String.slice和String.substring有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有谁知道这两种方法之间的区别:
Does anyone know what the difference is between these two methods:
String.protorype.slice
String.protorype.substring
推荐答案
slice( )
的作用类似于 substring()
,但有一些不同的行为。
slice()
works like substring()
with a few different behaviors.
Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);
他们有什么共同点:
- 如果
开始
等于停止
:返回一个空字符串 - 如果省略
stop
:将字符提取到字符串的末尾 - 如果任一参数大于字符串的长度,将使用字符串的长度。
- If
start
equalsstop
: returns an empty string - If
stop
is omitted: extracts characters to the end of the string - If either argument is greater than the string's length, the string's length will be used instead.
区别 substring()
:
- 如果
开始>停止
,然后substring
将交换这两个参数。 - 如果任一参数为负数或
NaN
,它被视为0
。
- If
start > stop
, thensubstring
will swap those 2 arguments. - If either argument is negative or is
NaN
, it is treated as if it were0
.
区分 slice()
:
- 如果
开始>停止
,slice()
将返回空字符串。 ()
- 如果
开始
为否定:设置来自的字符串的结尾,与Firefox中的substr()
完全相同。在Firefox和IE中都会出现此行为。 - 如果
stop
为负:将stop设置为:string .length - Math.abs(停止)
(原始值),但限制为0(因此,Math.max(0,string.length + stop)$ c ECMA中涵盖的$ c>)规范。
- If
start > stop
,slice()
will return the empty string. (""
) - If
start
is negative: sets char from the end of string, exactly likesubstr()
in Firefox. This behavior is observed in both Firefox and 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.
资料来源:编程的基本艺术&开发:Javascript:substr()v.s. substring()
这篇关于String.slice和String.substring有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文