Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

javascript - String.slice和String.substring有什么区别?(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
  ask by tmim translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(他们有什么共同点:)

  1. If start equals stop : returns an empty string

    (如果start equals stop :返回一个空字符串)

  2. If stop is omitted: extracts characters to the end of the string

    (如果省略stop :将字符提取到字符串的末尾)

  3. If either argument is greater than the string's length, the string's length will be used instead.

    (如果任一参数大于字符串的长度,则将使用字符串的长度。)

Distinctions of substring() :

(substring() 区别 )

  1. If start > stop , then substring will swap those 2 arguments.

    (如果start > stop ,那么substring将交换这两个参数。)

  2. If either argument is negative or is NaN , it is treated as if it were 0 .

    (如果任一参数为负数或为NaN ,则将其视为0 。)

Distinctions of slice() :

(slice() 区别 )

  1. If start > stop , slice() will return the empty string.

    (如果start > stopslice()将返回空字符串。)

    ( "" )

    (( "" ))

  2. 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中都观察到此行为。)

  3. 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())


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...