Learn JavaScript
❯ strings_regex.slice_substring

slice, substring & at() in JavaScript

$concept

Three slicers with subtly different contracts: slice(start, end) supports negatives (from the end) and swaps nothing — the modern default; substring(start, end) clamps negatives to 0 and swaps reversed bounds (legacy quirks to know, not use); substr(start, length) is deprecated legacy. New code uses slice almost exclusively.

All return new strings without touching the original, and end-exclusive ranges compose with indexOf results directly. For grapheme-correct slicing (emoji), operate on [...s] arrays instead of raw indexes.

$how it works
1

slice is the default

s.slice(1, 4), s.slice(2), s.slice(-3) — negatives count from the end, end-exclusive, no mutation.

2

substring quirks

Clamps negatives to 0 and swaps reversed args — legacy behavior to recognize, not to write.

3

substr is deprecated

Length-based second arg, still found in old code — replace with slice on sight.

4

Mind the units

All three count UTF-16 units — emoji-adjacent slicing needs code-point arrays first.

$example
let s = "hello";
console.log(s.slice(1, 4));
console.log(s.slice(-2));
Output
ell
lo
1slice(1, 4) copies indexes 1–3 (end-exclusive): ell.
2slice(-2) counts from the end, taking the last two characters: lo.
3Both print — positive ranges and negative from-the-end in one glance.
$use cases
Extracting substrings with negative-from-end indexes
Trimming known prefixes/suffixes by measured slice
Replacing legacy substring/substr on sight
Grapheme-safe slicing via spread arrays for emoji text

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.