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

发布于 2024-08-21 16:48:28 字数 98 浏览 9 评论 0原文

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

String.prototype.slice
String.prototype.substring

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

String.prototype.slice
String.prototype.substring

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

来世叙缘 2024-08-28 16:48:28

slice() 的工作方式与 substring() 类似,但有一些不同的行为。

Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);

它们的共同点:

  1. 如果 start 等于 stop:返回空字符串
  2. 如果省略 stop:提取字符到字符串末尾
  3. 如果任一参数大于字符串的长度,则将使用字符串的长度。

区别 substring():

  1. 如果 start >; stop,然后 substring 将交换这两个参数。
  2. 如果任一参数为负数或 NaN,则将其视为 0

区别 slice():

  1. 如果 start > stopslice() 将返回空字符串。 ("")
  2. 如果 start 为负数:从字符串末尾设置 char,与 substr() 完全相同。
  3. 如果 stop 为负数:将 stop 设置为:string.length – Math.abs(stop)(原始值),除了以 0 为界(因此,Math. max(0, string.length + stop)),如 ECMA 规范

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

slice() works like substring() with a few different behaviors.

Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);

What they have in common:

  1. If start equals stop: returns an empty string
  2. If stop is 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.

Distinctions of substring():

  1. If start > stop, then substring will swap those 2 arguments.
  2. If either argument is negative or is NaN, it is treated as if it were 0.

Distinctions of slice():

  1. If start > stop, slice() will return the empty string. ("")
  2. If start is negative: sets char from the end of string, exactly like substr().
  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.

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

追我者格杀勿论 2024-08-28 16:48:28

TL;DR:

  • 如果您知道要停止(但不包括)的索引(位置),请使用 slice()
  • 如果您知道要提取的字符长度,则可以使用 substr(),但不鼓励这样做,因为它已被弃用。

否则,请继续阅读以进行完整比较

语法

  • string.slice(start,end)
  • string.substr(start,length)
  • string.substring(start,end)

注意#1slice()==substring()

它的作用是什么?

  • slice() 提取字符串的一部分,并在新字符串中返回提取的部分。
  • substr() 从指定位置的字符开始提取字符串的一部分,并返回指定数量的字符。
  • substring() 提取字符串的一部分并在新字符串中返回提取的部分。

注意#2slice()==substring()

更改原始字符串?

  • slice() 不会
  • substr() 不会
  • substring() 不会

注意#3slice()==substr()==substring()

使用负数作为参数

  • slice() 选择从字符串末尾开始的字符
  • substr( ) 选择从字符串末尾开始的字符
  • substring() 不执行

注意#4slice()==substr()

如果第一个参数大于第二个,

  • slice() 不会执行
  • substr(),因为第二个参数不是位置,而是长度值,它将像往常一样执行,没有任何问题
  • substring() 将交换两个参数,并像往常一样执行

第一个参数

  • slice() 所需的; 需要起始索引
  • substr(); 需要起始索引
  • substring();起始索引

注释#5slice()==substr()==substring()

第二个参数

  • slice() 可选;结束提取的位置(最多但不包括)
  • substr() 可选;要提取的字符数
  • substring() 可选;结束提取的位置(最多但不包括)

注意#6slice()==substring()

如果省略第二个参数怎么办?

  • slice() 选择从字符串起始位置到结尾的所有字符
  • substr() 选择从字符串起始位置到结尾的所有字符
  • >substring() 选择从字符串起始位置到末尾的所有字符

注意#7slice()==substr()==substring()< /code>

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

如果您想要 substr 的功能:

"foobarbaz".substr(index, length);

在不使用已弃用的功能的情况下,您可以这样做:

"foobarbaz".substring(index, length + index);

并获得完全相同的结果,排除所有边缘情况,例如负索引/长度。

TL;DR:

  • 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, you could use substr(), but that is discouraged as it is deprecated.

Otherwise, read on for a full comparison

Syntax

  • string.slice(start,end)
  • string.substr(start,length)
  • string.substring(start,end)

Note #1: slice()==substring()

What it does?

  • slice() extracts parts of a string and returns the extracted parts in a new string.
  • substr() extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
  • substring() extracts parts of a string and returns the extracted parts in a new string.

Note #2: slice()==substring()

Changes the Original String?

  • slice() doesn't
  • substr() doesn't
  • substring() doesn't

Note #3: slice()==substr()==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 #4: 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

The First Argument

  • slice() required; starting Index
  • substr() required; starting Index
  • substring() required; starting Index

Note #5: 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 #6: 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 #7: slice()==substr()==substring()

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

If you want substr's functionality:

"foobarbaz".substr(index, length);

without using a deprecated feature, you can just do:

"foobarbaz".substring(index, length + index);

And get the exact same results bar all of the edge-cases, like negative index/length.

冰雪之触 2024-08-28 16:48:28

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

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

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

这是他的文章这。

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

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.

Here is his article about this.

负佳期 2024-08-28 16:48:28

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

我的Go——按差异组织,使其除了上面丹尼尔的第一个答案之外也有用:

1)负索引。 Substring 需要正索引,并将负索引设置为 0。Slice 的负索引表示距离字符串末尾的位置。

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

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

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

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

一般评论 -- 我觉得很奇怪,第二个索引是切片或子字符串的最后一个字符之后的位置。我希望“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。

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:

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.

"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.

"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) == "", "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.

是你 2024-08-28 16:48:28

substringslice 之间的区别在于它们如何处理负参数和忽略行外部参数:

substring(start, end)

负参数被解释为零。太大的值将被截断为字符串的长度:

alert("testme".substring(-2)); // "testme", -2 becomes 0

此外,如果 start > end,参数互换,即绘图线在start和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

从行尾开始测量负值:

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.

比奇怪的逻辑substring<方便多了/代码>。

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

如果选择这三种方法之一,则适用于大多数情况 - 它将是slice:负参数,并且它的维护和操作最为明显。

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

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

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-.

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.

终难愈 2024-08-28 16:48:28

substr:它允许我们根据指定的索引获取字符串的一部分。
substr 的语法
字符串.substr(开始,结束)
start - 开始索引告诉从哪里开始获取。
end - 结束索引告诉字符串的提取位置。这是可选的。

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

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

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

output: crip

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

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

output: avas

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

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.

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.

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.]

鼻尖触碰 2024-08-28 16:48:28

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

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

您不能将负值作为 substring 方法的第一个参数传递,但要让 slice 方法从末尾遍历它。

Slice 方法参数详细信息:

参数

start_index
切片应开始的索引。如果提供负值,则表示从最后一个开始。例如 -1 代表最后一个字符。
结束索引
切片结束后的索引。如果未提供切片,将从 start_index 到字符串末尾进行切片。如果是负值,索引将从字符串末尾开始测量。

子字符串方法参数详细信息:

参数

来自
它应该是一个非负整数来指定子字符串应该开始的索引。

一个可选的非负整数,用于提供子字符串应在其之前完成的索引。

The only difference between slice and substring method is of arguments

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

You cannot pass a negative value as first argument for substring method but for slice method to traverse it from end.

Slice method argument details:

Arguments

start_index
Index from where slice should begin. If value is provided in negative it means start from last. e.g. -1 for last character.
end_index
Index 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.

Substring method argument details:

Arguments

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

败给现实 2024-08-28 16:48:28

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

string.length – Math.abs(stop)

而不是:

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

For slice(start, stop), if stop is negative, stop will be set to:

string.length – Math.abs(stop)

rather than:

string.length – 1 – Math.abs(stop)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文