Strings
split() and join()
Turn a string into an array of pieces and back.
Why it exists
Many strings are really lists: comma-separated tags, space-separated words, a CSV row, a path like /blog/2024/js. Working with them as strings is awkward, while arrays have everything you need: map, filter, length. split turns the string into an array, you process the items, and join puts the result back into a string. This pair is the basis of almost any text processing.
Where it's used
- Tags and lists:
"js, css, html".split(", "). - Words in a text: counting, capitalizing, searching.
- CSV and log lines:
line.split(";"). - Building text:
items.join(", ")→ "tea, coffee, sugar" with no stray comma at the end.
Syntax
string.split(separator)
array.join(separator)Examples
"a,b,c".split(","); // → ["a", "b", "c"]
["2024", "05", "17"].join("-"); // → "2024-05-17"const tags = "js, css, html".split(", ");
tags; // → ["js", "css", "html"]
tags.length; // → 3"hello world".split(" ").map((w) => w.toUpperCase()).join(" "); // → "HELLO WORLD""a b".split(" "); // → ["a", "", "b"]
"".split(" "); // → [""]
"cat".split(""); // → ["c", "a", "t"]Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
split looks for the separator in the string and cuts at every occurrence. The separator doesn't end up in the result. If two separators are side by side, you get an empty string "" between them — that's why double spaces give "empty words".
Special cases: split("") cuts into single characters; for an empty string, "".split(",") gives not an empty array but [""].
join is the reverse: it puts the separator between items (not after the last one). Without an argument the separator is a comma. Numbers and other values are turned into strings.
split is a string method, join an array method. Both return new values and change nothing.
Traps
How it differs from…
- Joining strings
Gluing items with
+in a loop means tracking the separator yourself, plus the stray comma at the end.joindoes it for you.array.map()map often sits between
splitandjoin: it changes each piece before the string is put back together.
When to pick something else
For parsing complex formats (CSV with commas inside quotes, JSON, URLs) split isn't enough — there are ready tools: JSON.parse, new URL(...), CSV libraries. And to just replace a character, replaceAll is shorter.
Practice
Lessons where this appears
- Why do regexes look like line noise?Why? · Chapter 7 · Regular expressions
- A page address from a titleLab · Chapter 7 · Regular expressions
- New versionLab · Chapter 25 · npm and packages
- The case of the missing customersInvestigation · Chapter 26 · Debugging
- Resolve the conflictLab · Chapter 28 · Git: the history of code