How does slice() work?
[String.prototype.slice()](developer.mozilla.org/en-US/docs/Web/JavaSc..) takes two parameters.
beginIndex— The index of the first character to return
endIndex— The index of the last character to return
'The quick brown fox'.slice(4, 9); // Returns 'quick'.
It may be helpful to think of an “index” as the spaces between characters, starting at zero.
endIndex is optional. If you leave it out,
.slice() will simply return characters all the way to the end of the string.
'The quick brown fox'.slice(4); // Return 'quick brown fox'.
I like using LEFT() and RIGHT() in other languages
Instead of writing
LEFT('The quick brown fox', 3), you can write…
'The quick brown fox'.slice(0, 3);
Instead of writing
RIGHT('The quick brown fox', 3);, you can write…
'The quick brown fox'.slice(-3);
This works because when
startIndex is negative,
.slice() starts from the end of the string and works backwards.
Why not substring()?
[String.prototype.substring()](developer.mozilla.org/en-US/docs/Web/JavaSc..) is very similar to
.slice(). There are two main differences.
If either parameter in
.substring() is negative, it’s treated as zero.
'The quick brown fox'.substring(-3); // Returns 'The quick brown fox'.
startIndex is greater than
.substring() will swap the two parameters. This is different than
.slice() which will simply return an empty string.
'The quick brown fox'.substring(9, 4); // Returns 'quick'. 'The quick brown fox'.slice(9, 4); // Returns '';
So why not use
.substring() instead? Well, simply because you have to choose one. And
String.prototype.slice() has a parallel method for arrays called
[Array.prototype.slice()](developer.mozilla.org/en-US/docs/Web/JavaSc..). Learning and using
.slice() means you can use it for two different datatypes.
I thought you said there were three methods?
There are. The last one is
[String.prototype.substr()](developer.mozilla.org/en-US/docs/Web/JavaSc..). It also takes two parameters. The first parameter is the usual start character index. But the second parameter is the length to extract.
'The quick brown fox'.substr(4, 5); // Returns 'quick'.
Keep it simple. Learn and use
.slice() for all your string and array slicing needs.