开发者

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

开发者 https://www.devze.com 2022-12-19 17:23 出处:网络
Doe开发者_C百科s anyone know what the difference is between these two methods? String.prototype.slice

Doe开发者_C百科s anyone know what the difference is between these two methods?

String.prototype.slice
String.prototype.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() in Firefox. This behavior is observed in both Firefox and 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.

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


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.


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.


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.


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.


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


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.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号