What is the difference between slice and substring on a string?
Both return part of a string without changing it. slice accepts negative indexes, counting from the end, and returns an empty string if start is after end. substring treats negatives as 0 and swaps its arguments if start is greater than end.
Explain it simply
Both pick out a piece of a string between a start index and an end index (the end is not included). They differ only in how forgiving they are.
substring is the tidy-minded one: it treats negative numbers as 0 and quietly swaps the arguments if they are the wrong way round. slice is stricter and more useful: a negative index counts back from the end, so slice(-4) means "the last four characters".
Prefer slice, since it behaves the same as Array.prototype.slice and is easier to predict. Avoid the old substr, which is deprecated.
Example
const s = "hello";
console.log(s.slice(1, 3)); // Output: el
console.log(s.substring(1, 3)); // Output: el
console.log(s.slice(3, 1) === ""); // Output: true
console.log(s.substring(3, 1)); // Output: el
console.log(s.slice(-2)); // Output: lo
console.log(s.substring(-2)); // Output: helloLast four digits of a number string: "9876543210".slice(-4) is "3210".
What to say in the interview
"slice and substring both take start and an exclusive end. slice supports negative indexes from the end and returns an empty string for a reversed range; substring clamps negatives to 0 and swaps reversed arguments. I use slice for consistency with arrays."
Common mistakes
- Using substring(-4) to get the last four characters. It returns the whole string.