Strings
slice()
Cuts a piece out of a string or array by index, without changing the original.
Why it exists
Very often you need part of a string, not all of it: the first letter, a card's last 4 digits, the first 100 characters for a preview, a file extension. slice gives you any piece by index — and breaks nothing: the original stays whole, so you can keep using it.
Where it's used
- Text previews:
text.slice(0, 100) + "…". - The last characters:
card.slice(-4)— a number's last digits. - "Everything but the first":
text.slice(1)— for example, to capitalize. - List pages:
items.slice(20, 30)— items 21 to 30.
Syntax
string.slice(start)
string.slice(start, end)
array.slice(start, end)Examples
const word = "JavaScript";
word.slice(0, 4); // → "Java"
word.slice(4); // → "Script"
word.slice(-3); // → "ipt"const card = "4276123456781234";
card.slice(-4); // → "1234"
card.slice(0, 4); // → "4276"const name = "ann";
name[0].toUpperCase() + name.slice(1); // → "Ann"const items = ["a", "b", "c", "d", "e"];
items.slice(1, 3); // → ["b", "c"]
items; // → ["a", "b", "c", "d", "e"] — the original is intactResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
slice(start, end) takes items from index start inclusive to end exclusive. So the piece's length is end - start, and slice(0, 4) is exactly four characters.
If end is omitted, the piece runs to the very end. A negative index counts from the end: -1 is the last item, -4 the fourth from the end.
Out-of-range indexes don't cause errors: "cat".slice(0, 100) just returns "cat", and "cat".slice(5) an empty string.
slice works the same on strings and arrays. It always returns a new value — the original string or array doesn't change.
Traps
How it differs from…
- Indexes and
length text[i]takes one character,slicea piece of any length. For the last character bothtext[text.length - 1]andtext.slice(-1)work.