Problem Statement
What is the difference between slice() and substring()?
Explanation
Slice and substring both extract parts of a string, but they handle arguments differently.
Slice accepts negative indices. Negative numbers count from the end of the string. For example, slice minus 3 gets the last 3 characters.
Substring treats negative numbers as zero. It does not support counting from the end.
If start is greater than end, substring swaps them automatically. Slice returns an empty string instead.
Both create new strings without modifying the original.
Slice is more versatile and commonly preferred.
Code Solution
SolutionRead Only
const str = 'Hello World'; // slice() - accepts negative indices console.log(str.slice(0, 5)); // 'Hello' console.log(str.slice(6)); // 'World' console.log(str.slice(-5)); // 'World' (last 5 chars) console.log(str.slice(-5, -1)); // 'Worl' (from end) // substring() - no negative support console.log(str.substring(0, 5)); // 'Hello' console.log(str.substring(6)); // 'World' console.log(str.substring(-5)); // 'Hello World' (treats -5 as 0) // Swapping behavior console.log(str.slice(5, 0)); // '' (empty string) console.log(str.substring(5, 0)); // 'Hello' (swaps to 0, 5) // Get last character console.log(str.slice(-1)); // 'd' console.log(str.substring(str.length - 1)); // 'd' // Both don't modify original const original = 'Test'; const sliced = original.slice(0, 2); console.log(original); // 'Test' (unchanged) console.log(sliced); // 'Te'
Practice Sets
This question appears in the following practice sets:
