What is the difference between slice() and substr() in JavaScript?

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.


  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