17

Can I ask what the difference is between string object slice() and substr() in JavaScript?

S.L. Barth
  • 7,954
  • 71
  • 47
  • 62
dramasea
  • 3,010
  • 14
  • 43
  • 71

5 Answers5

34

They have different signatures, .slice() is:

string.slice(beginIndex, endIndex)

Whereas .substr() is:

string.substr(beginIndex, length);

So for example, if we have "1234" and wanted "23", it would be:

"1234".slice(1,3)
//or...
"1234".substr(1,2)

They also have different behavior for the more-rarely used negative indexes, look at the MDC documentation for .slice() and .substr() for full descriptions.

Zsolt Meszaros
  • 8,506
  • 12
  • 20
  • 30
Nick Craver
  • 594,859
  • 130
  • 1,270
  • 1,139
  • 2
    Note that the "substr" method is not a part of ECMAScript standard and also can give inconsistent results in different browsers. Here is good summary: http://www.jacklmoore.com/notes/substring-substr-slice-javascript/ – C-F Jun 12 '13 at 02:54
5
  1. String.slice(begin, end)

    This method will cut text from begin to end char, eg.:

    alert("Hello World!".slice(1, 8)); // ello Wo
    
  2. String.substr(begin, length)

    This method will cut text from begin to begin + length char, eg.:

    alert("Hello World!".substr(1, 8)); // ello Wor
    
Crozin
  • 41,538
  • 12
  • 84
  • 134
2
var str="Hello world!";
document.write(str.substring(3,7)+"<br />");
document.write(str.slice(3,7)+"<br />");
document.write(str.substr(3,7));

result:

lo w
lo w
lo worl
Dungeon Hunter
  • 17,873
  • 13
  • 53
  • 78
Jon
  • 21
  • 2
1

Substring()

1.If start equals stop, it returns an empty string. 2.If stop is omitted, it extracts characters to the end of the string. 3.If start > stop, then substring will swap those 2 arguments. 4.If either argument is greater than the string's length, either argument will use the string's length. 5.If either argument is less than 0 or is NaN, it is treated as if it were 0.

slice()

1.If start equals stop, it returns an empty string, exactly like substring(). 2.If stop is omitted, slice extracts chars to the end of the string, exactly like substring(). 3.If start > stop, slice() will NOT swap the 2 arguments. 4.If either argument is greater than the string's length, either argument will use the string's length, exactly like substring().

anjaly
  • 508
  • 5
  • 11
0

I think the difference between str.slice() and str.substr() is the second parameter:

.slice() takes EndIndex while .substr() takes length as in:

.slice(StartIndex,EndIndex) and .substr(StartIndex,length).

shadowBot
  • 109
  • 1
  • 6