Can I ask what the difference is between string object slice()
and substr()
in JavaScript?
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.
JavaScript Array slice() The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.
The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.
Definition and UsageThe substring() method extracts characters, between two indices (positions), from a string, and returns the substring. The substring() method extracts characters from start to end (exclusive). The substring() method does not change the original string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With