JavaScript slice() and substring(): Text Ranges
Quick answer
Both methods return a new string from an index range; the start is inclusive and the end is exclusive. Their treatment of negative or reversed bounds differs.
How it works
slice(start, end) interprets negative offsets relative to length and returns an empty string when the normalized end precedes the start. substring(start, end) clamps negative bounds to zero and swaps reversed bounds. Omitted end means length. Neither method mutates the original.
const text = "notebook";console.log(text.slice(0, 4), text.slice(-4));Expected output in Node.js:
note bookThe first range excludes index 4; the second starts four units from the end.
const text = "abcdef";console.log(text.slice(4, 1) === "", text.substring(4, 1));Expected output in Node.js:
true bcdslice keeps direction, while substring swaps the bounds.
Common mistakes
An end index is not a count. Both operate on code units and may split a surrogate pair.
Practice
Extract a three-unit product prefix and a two-unit suffix without changing the input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript slice() and substring(): Text Ranges — Knowledge Check
Apply the taught concept and predict the output.
How does substring treat a negative start?
Which boundary is excluded by both extraction methods?
What does slice(-2) do on a six-unit string?
What is the exact console output in JavaScript slice() and substring(): Text Ranges example 1?
const text = "notebook";console.log(text.slice(0, 4), text.slice(-4));What is the exact console output in JavaScript slice() and substring(): Text Ranges example 2?
const text = "abcdef";console.log(text.slice(4, 1) === "", text.substring(4, 1));