926

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

String.prototype.slice
String.prototype.substring
Arsen Khachaturyan
  • 6,472
  • 4
  • 32
  • 36
tmim
  • 9,711
  • 4
  • 16
  • 12
  • 253
    It's an example of the poor design of JavaScript that we ended up with three methods that all do the same thing, but with different quirks. IMO `slice` is the one with the least unexpected behaviour. – bobince Feb 11 '10 at 15:53
  • 2
    IMO substring when used to take a substring from idx till end is more understandable at a glance. Especially to noobs – mplungjan Jul 06 '11 at 13:12
  • 1
    According to [this website](http://www.bennadel.com/blog/2159-Using-Slice-Substring-And-Substr-In-Javascript.htm), `slice` can actually replace `substring` and there is no reason to use it. – Derek 朕會功夫 Jul 08 '12 at 22:36
  • 1
    The `slice` & `substring` methods are all most the same; except the that the `slice()` accepts a negative index, relative to the end of the string, but not the `substring`, it throws `out-of-bound` error – Amol M Kulkarni Apr 09 '13 at 09:46
  • 5
    @AmolMKulkarni Not true at all. If you try `var a = "asdf".substring(-1);`, it's treated as `var a = "asdf".substring(0);`. There's no exception thrown. And if you use `var a = "asdf".substring(2, -1);`, it uses `0` in place of `-1` (like before), and swaps the arguments so it acts like `var a = "asdf".substring(0, 2);`. I even tried these on IE 8 and got the results with no exceptions – Ian Jul 17 '13 at 17:38
  • 42
    "I even tried these on IE 8" - I love programming. – quemeful Mar 14 '15 at 14:55

8 Answers8

946

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

Solomon Ucko
  • 2,682
  • 2
  • 14
  • 27
Daniel Vassallo
  • 312,534
  • 70
  • 486
  • 432
  • 9
    In your last note on `slice()`, it should be `string.length - stop` – Andy Feb 14 '12 at 15:16
  • 17
    In your last note on `slice()`, I think it should be `(string.length – 1) + stop` or, to make it clear that it's negative, `(string.length – 1) – Math.abs(stop)` – Oriol Sep 01 '12 at 17:46
  • 10
    @Longpoke: `String.slice` was added so that there is a string method consistent to `Array.slice`. `substring` has been there forever, so they didn’t break it and added another method. Hardly a crappy decision as 1. consistency is nice and 2. it allows CoffeeScript’s slicing syntax to work on arrays and strings. @Oriol: edited it in. – flying sheep Jan 13 '13 at 21:34
  • 6
    It seems there's a performance difference between substring and slice in Firefox 22. http://jsperf.com/string-slice-vs-substring – Rick Jul 17 '13 at 21:29
  • 2
    They are equaly fast in Chrome as of May 2014. – Qwerty May 09 '14 at 09:10
  • I like how `substring` allows for interchangeable arguments. – Max Nov 30 '14 at 21:47
  • 4
    Andy was right. `stop` will be set to `string.length + stop` if `stop` is negative. Remember `stop` is the index after the last character extracted! – user1537366 Dec 09 '14 at 15:53
  • 1
    @DanielVassallo You should really edit it. It's wrong. – user1537366 Feb 08 '15 at 06:13
  • 1
    It looks like point 5 on `substr` is incorrect, according to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr): "If start is negative, substr() uses it as a character index from the end of the string. If start is negative and abs(start) is larger than the length of the string, substr() uses 0 as the start index." – IanVS Aug 09 '16 at 14:38
  • 1
    Can we have a moderator please edit the last #3 point in the answer above? It is verifiably incorrect, but the author is not fixing it. Proof: `"abc".slice(0, -1)` equals `"ab"`, NOT `"a"` as his answer indicates. – Venryx Apr 22 '17 at 09:49
  • 1
    Wow, how come nobody spotted that so far? The statement "If `start > stop`, `slice()` will return the empty string" is wrong. For example: `4 > -1`, but `"babayaga".slice(4, -1)` returns `"yag"`. – goodvibration Jul 13 '19 at 13:10
  • @goodvibration So the problem with the answer is that rule #3 should go first or should be noted as an exception to rule #1. – snuggles Feb 17 '20 at 12:09
112

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

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

Changes the Original String?
slice() Doesn't
substr() Doesn't
substring() Doesn't
Note #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()

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, indicates: Starting Index
substr() Required, indicates: Starting Index
substring() Required, indicates: Starting Index
Note #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()

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

so, you can say that there's a difference between slice() and substr(), while substring() is basically a copy of 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().

Naetmul
  • 11,923
  • 6
  • 46
  • 72
Waddah
  • 1,585
  • 1
  • 10
  • 5
  • 23
    substr() should not be used https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr – Killy Jul 11 '19 at 10:23
  • @Killy [Source regarding it being a legacy feature](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) Not mentioned in your link. – CodeFinity Aug 10 '20 at 17:12
  • You summarize your lengthy answer by "substring() is basically a copy of slice()", but the question was precisely about the difference between these two. The rest of your answer misses the topic, apart the *only* relevant piece information "slice will swap the arguments" hidden somewhere in the middle. – Max Dec 08 '20 at 18:21
  • @CodeFinity when I wrote the post there was a comment about, but somebody removed it in july 2020 https://web.archive.org/web/20200704195437/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr – Killy Feb 10 '21 at 14:49
  • @Killy: It is still in the compatibility table as well as the side-bar. There is inconsistency in the banners. No idea why someone removed it from one but not the others or vice versa. The inconsistency is a bit unfortunate. Banner is present on all the others. In short `substr` is part of Annex B of the ECMA standard hence not mart of the core. It gives a note for it's usage: https://262.ecma-international.org/9.0/#sec-additional-ecmascript-features-for-web-browsers - MDN note: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#string_methods – user3342816 Mar 05 '21 at 18:00
  • @CodeFinity: My comment above for you as well :), was no room left. Here is link to current ECMA draft as well: https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers - guess the removal of banner is due to «probably won't be removed anytime soon» in MDN link. I still find the inconsistency a bit unfortunate – should perhaps be another banner for similar cases (where not legacy, but likely to remain for quite a while.) – Personally I just realized it after the fact and am in the process of refactoring 1k lines of new code from substr to slice lol. – user3342816 Mar 05 '21 at 18:14
33

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.

Pang
  • 8,605
  • 144
  • 77
  • 113
15

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.

AmerllicA
  • 15,720
  • 11
  • 72
  • 103
Gerard ONeill
  • 3,193
  • 31
  • 22
11

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.

Alexandr
  • 4,604
  • 3
  • 37
  • 65
3

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:

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

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:

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

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.

Sohail Arif
  • 233
  • 1
  • 9
3

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

Ashraf Sada
  • 3,511
  • 1
  • 36
  • 43
subham ruj
  • 47
  • 1
  • 2
  • What you wrote is wrong AND not relevant for the question. substr() is a different function, it does NOT have parameters "start, stop" as you erroneously state in your answer: it has parameters "start, length". But the question is not at all about substr()! Fortunately a correct and complete answer was already given 9 years before... – Max Dec 08 '20 at 18:32
0

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)
MarredCheese
  • 9,495
  • 5
  • 59
  • 63
tingxuanz
  • 196
  • 7