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

dramasea picture dramasea · Dec 28, 2010 · Viewed 8.4k times · Source

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

Answer

Nick Craver picture Nick Craver · Dec 28, 2010

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.