Javascript String.slice 和 String.substring 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2243824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:26:10  来源:igfitidea点击:

What is the difference between String.slice and String.substring?

javascriptsubstringslicesubstr

提问by tmim

Does anyone know what the difference is between these two methods?

有谁知道这两种方法有什么区别?

String.prototype.slice
String.prototype.substring

回答by Daniel Vassallo

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 startequals stop: returns an empty string
  2. If stopis omitted: extracts characters to the end of the string
  3. If either argument is greater than the string's length, the string's length will be used instead.
  1. 如果start等于stop:返回一个空字符串
  2. 如果stop省略:将字符提取到字符串的末尾
  3. 如果任一参数大于字符串的长度,则将使用字符串的长度。

Distinctions ofsubstring():

的区别substring()

  1. If start > stop, then substringwill swap those 2 arguments.
  2. If either argument is negative or is NaN, it is treated as if it were 0.
  1. 如果start > stopsubstring则将交换这两个参数。
  2. 如果任一参数为负或为NaN,则将其视为0

Distinctions ofslice():

的区别slice()

  1. If start > stop, slice()will return the empty string. ("")
  2. If startis negative: sets char from the end of string, exactly like substr()in Firefox. This behavior is observed in both Firefox and IE.
  3. If stopis 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.
  1. 如果start > stop,slice()将返回空字符串。( "")
  2. 如果start为负:从字符串的末尾设置字符,就像substr()在 Firefox 中一样。在 Firefox 和 IE 中都可以观察到这种行为。
  3. 如果stop为负:将停止设置为:(string.length – Math.abs(stop)原始值),除非ECMA 规范中Math.max(0, string.length + stop)涵盖的以 0为界(因此,)。

Source: Rudimentary Art of Programming & Development: Javascript: substr() v.s. substring()

资料来源:编程与开发的基本艺术:Javascript:substr() 与 substring()

回答by Waddah

Note: if you're in a hurry, and/or looking for short answer scroll to the bottom of the answer, and read the last two lines.if Not in a hurry read the whole thing.


let me start by stating the facts:

注意:如果你很着急,和/或寻找简短的答案,请滚动到答案的底部,然后阅读最后两行。如果不着急,请阅读整篇文章。


首先让我陈述事实:

Syntax:
string.slice(start,end)
string.substr(start,length)
string.substring(start,end)
Note #1: slice()==substring()

语法:
string.slice(start,end)
string.substr(start,length)
string.substring(start,end)
注意 #1:slice()==substring()

What it does?
The slice()method extracts parts of a string and returns the extracted parts in a new string.
The substr()method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
The substring()method extracts parts of a string and returns the extracted parts in a new string.
Note #2:slice()==substring()

它能做什么?
slice()方法提取字符串的一部分并在新字符串中返回提取的部分。
substr()方法从指定位置的字符开始提取字符串的一部分,并返回指定数量的字符。
substring()方法提取字符串的一部分并在新字符串中返回提取的部分。
笔记2:slice()==substring()

Changes the Original String?
slice()Doesn't
substr()Doesn't
substring()Doesn't
Note #3:slice()==substring()

更改原始字符串?
slice()
substr()
substring()
注3:slice()==substring()

Using Negative Numbers as an Argument:
slice()selects characters starting from the end of the string
substr()selects characters starting from the end of the string
substring()Doesn't Perform
Note #3:slice()==substr()

使用负数作为参数:
slice()选择从字符串末尾开始的字符
substr()选择从字符串末尾开始的字符
substring()不执行
注 #3:slice()==substr()

if the First Argument is Greater than the Second:
slice()Doesn't Perform
substr()since the Second Argument is NOT a position, but length value, it will perform as usual, with no problems
substring()will swap the two arguments, and perform as usual

如果第一个参数大于第二个:
slice()不执行,
substr()因为第二个参数不是位置,而是长度值,它将照常执行,没有问题
substring()将交换两个参数,并照常执行

the First Argument:
slice()Required, indicates: Starting Index
substr()Required, indicates: Starting Index
substring()Required, indicates: Starting Index
Note #4:slice()==substr()==substring()

第一个参数:
slice()必需,表示:需要开始索引
substr(),表示:需要开始索引
substring(),表示:开始索引
注意#4:slice()==substr()==substring()

the Second Argument:
slice()Optional, The position (up to, but not including) where to end the extraction
substr()Optional, The number of characters to extract
substring()Optional, The position (up to, but not including) where to end the extraction
Note #5:slice()==substring()

第二个参数:
slice()可选,提取结束的位置(最多但不包括)
substr()可选,提取的字符数 可选,提取结束的
substring()位置(最多但不包括)
注 #5:slice()==substring()

What if the Second Argument is Omitted?
slice()selects all characters from the start-position to the end of the string
substr()selects all characters from the start-position to the end of the string
substring()selects all characters from the start-position to the end of the string
Note #6:slice()==substr()==substring()

如果省略第二个参数怎么办?
slice()选择从开始位置到字符串末尾的
substr()所有字符 选择从开始位置到字符串末尾的
substring()所有字符 选择从开始位置到字符串末尾的所有字符
注意 #6:slice()==substr()==substring()

so, you can say that there's a difference between slice()and substr(), while substring()is basically a copy of slice().

因此,您可以说slice()和之间存在差异substr(),而substring()基本上是 的副本slice()

in Summary:
if you know the index(the position) on which you'll stop (but NOT include), Use slice()
if you know the length of characters to be extracted use substr().

总结:
如果您知道将停止(但不包括)的索引(位置),slice()
如果您知道要提取的字符的长度,请使用substr().

回答by Jón Viear Torsteinsson

Ben Nadel has written a good article about this, he points out the difference in the parameters to these functions:

Ben Nadel 写了一篇关于这个的好文章,他指出了这些函数的参数差异:

String.slice( begin [, end ] )
String.substring( from [, to ] )
String.substr( start [, length ] )

He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn′t.

他还指出,如果切片的参数为负,则它们从末尾引用字符串。Substring 和 substr 没有。

Hereis his article about this.

是他关于此的文章。

回答by Gerard ONeill

The one answer is fine but requires a little reading into. Especially with the new terminology "stop".

一个答案很好,但需要一点点阅读。尤其是新术语“停止”。

My Go -- organized by differences to make it useful in addition to the first answer by Daniel above:

我的 Go - 除了上面 Daniel 的第一个答案之外,还按差异进行组织以使其有用:

1) negative indexes. Substring requires positive indexes and will set a negative index to 0. Slice's negative index means the position from the end of the string.

1) 负面指标。Substring 需要正索引,并将负索引设置为 0。Slice 的负索引表示从字符串末尾开始的位置。

"1234".substring(-2, -1) == "1234".substring(0,0) == ""
"1234".slice(-2, -1) == "1234".slice(2, 3) == "3"

2) Swapping of indexes. Substring will reorder the indexes to make the first index less than or equal to the second index.

2)交换索引。Substring 将对索引重新排序,使第一个索引小于或等于第二个索引。

"1234".substring(3,2) == "1234".substring(2,3) == "3"
"1234".slice(3,2) == ""

--------------------------

--------------------------

General comment -- I find it weird that the second index is the position after the last character of the slice or substring. I would expect "1234".slice(2,2) to return "3". This makes Andy's confusion above justified -- I would expect "1234".slice(2, -1) to return "34". Yes, this means I'm new to Javascript. This means also this behavior:

一般评论——我觉得奇怪的是,第二个索引是切片或子字符串的最后一个字符之后的位置。我希望 "1234".slice(2,2) 返回 "3"。这使得安迪的上述混淆是合理的——我希望 "1234".slice(2, -1) 返回 "34"。是的,这意味着我是 Javascript 的新手。这也意味着这种行为:

"1234".slice(-2, -2) == "", "1234".slice(-2, -1) == "3", "1234".slice(-2, -0) == "" <-- you have to use length or omit the argument to get the 4.
"1234".slice(3, -2) == "", "1234".slice(3, -1) == "", "1234".slice(3, -0) == "" <-- same issue, but seems weirder.

My 2c.

我的2c。

回答by Alexandr

The difference between substring and slice - is how they work with negative and overlooking lines abroad arguments:

substring 和 slice 之间的区别 - 是它们如何处理国外参数的否定和忽略行:

substring (start, end)

子串(开始,结束)

Negative arguments are interpreted as zero. Too large values ??are truncated to the length of the string: ? alert ( "testme" .substring (-2)); // "testme", -2 becomes 0

负参数被解释为零。太大的值被截断为字符串的长度: ? 警报(“testme”.substring(-2));// "testme", -2 变为 0

Furthermore, if start > end, the arguments are interchanged, i.e. plot line returns between the start and end:

此外,如果开始 > 结束,则参数互换,即绘图线在开始和结束之间返回:

alert ( "testme" .substring (4, -1)); // "test"
// -1 Becomes 0 -> got substring (4, 0)
// 4> 0, so that the arguments are swapped -> substring (0, 4) = "test"

slice

Negative values ??are measured from the end of the line:

负值是从行尾开始测量的:

alert ( "testme" .slice (-2)); // "me", from the end position 2
alert ( "testme" .slice (1, -1)); // "estm", from the first position to the one at the end.

It is much more convenient than the strange logic substring.

它比奇怪的逻辑子串方便得多。

A negative value of the first parameter to substr supported in all browsers except IE8-.

除 IE8- 之外的所有浏览器都支持 substr 的第一个参数的负值。

If the choice of one of these three methods, for use in most situations - it will be slice: negative arguments and it maintains and operates most obvious.

如果选择这三种方法中的一种,在大多数情况下使用 - 它将是slice:negative arguments 并且它维护和操作最明显。

回答by Sohail Arif

The only difference between slice and substring method is of arguments

slice 和 substring 方法之间的唯一区别是参数

Both take two arguments e.g. start/from and end/to.

两者都采用两个参数,例如 start/from 和 end/to。

You cannot pass a negative value as first argument for substringmethod but for slicemethod to traverse it from end.

您不能将负值作为子字符串方法的第一个参数传递,但切片方法可以从末尾遍历它。

Slice method argument details:

切片方法参数详细信息:

REF: http://www.thesstech.com/javascript/string_slice_method

参考:http: //www.thesstech.com/javascript/string_slice_method

Arguments

参数

start_indexIndex from where slice should begin. If value is provided in negative it means start from last. e.g. -1 for last character. end_indexIndex after end of slice. If not provided slice will be taken from start_index to end of string. In case of negative value index will be measured from end of string.

start_index切片应该从哪里开始的索引。如果值以负数提供,则表示从最后开始。例如 -1 表示最后一个字符。 end_index切片结束后的索引。如果没有提供切片将从 start_index 到字符串的结尾。在负值的情况下,索引将从字符串的末尾开始测量。

Substring method argument details:

子串方法参数详细信息:

REF: http://www.thesstech.com/javascript/string_substring_method

参考:http: //www.thesstech.com/javascript/string_substring_method

Arguments

参数

fromIt should be a non negative integer to specify index from where sub-string should start. toAn optional non negative integer to provide index before which sub-string should be finished.

from它应该是一个非负整数,用于指定子字符串应该从哪里开始的索引。 to一个可选的非负整数,用于提供应该在子字符串之前完成的索引。

回答by subham ruj

substr: It's providing us to fetch part of the string based on specified index. syntax of substr- string.substr(start,end) start - start index tells where the fetching start. end - end index tells upto where string fetches. It's optional.

substr:它使我们能够根据指定的索引获取部分字符串。substr-string.substr(start,end) start - start index 的语法说明了获取的开始位置。结束 - 结束索引告诉最多字符串获取的位置。它是可选的。

slice: It's providing to fetch part of the string based on the specified index. It's allows us to specify positive and index. syntax of slice - string.slice(start,end) start - start index tells where the fetching start.It's end - end index tells upto where string fetches. It's optional. In 'splice' both start and end index helps to take positive and negative index.

slice:它提供根据指定的索引获取部分字符串。它允许我们指定正数和索引。切片的语法 - string.slice(start,end) start - start - 开始索引告诉获取开始的位置。它的结束 - 结束索引告诉字符串获取的位置。它是可选的。在“拼接”中,开始和结束索引都有助于采用正索引和负索引。

sample code for 'slice' in string

字符串中“切片”的示例代码

var str="Javascript";
console.log(str.slice(-5,-1));

output: crip

sample code for 'substring' in string

字符串中“子字符串”的示例代码

var str="Javascript";
console.log(str.substring(1,5));

output: avas

[*Note: negative indexing starts at the end of the string.]

[*注意:负索引从字符串的末尾开始。]

回答by tingxuanz

For slice(start, stop), if stopis negative, stopwill be set to:

对于slice(start, stop),如果stop为负,stop将设置为:

string.length – Math.abs(stop)

rather than:

而不是:

string.length – 1 – Math.abs(stop)