Sub topic 8
Splitting Strings and Joining Arrays
This chapter assumes you can write functions, use array methods such as map and filter, and run code in Node.js or a browser console. You should also know slice and indexOf from the earlier chapters. Regular expression syntax helps for one section, and a later chapter covers it in depth.
Many text tasks follow one pattern: break a string into pieces, work on the pieces as an array, then put them back together. String.prototype.split handles the first step and Array.prototype.join handles the last. Because strings are immutable, neither method changes its input. split returns a new array, and join returns a new string.
The basic round trip
Here is the most common use. You split a comma-separated string, clean each piece, and join the pieces with a different separator.
const csv = " alice, bob ,carol ";
const names = csv.split(",").map((n) => n.trim());
console.log(names); // ["alice", "bob", "carol"]
console.log(names.join(" | ")); // alice | bob | carol
console.log("7".padStart(3, "0")); // 007
console.log("ab".repeat(3)); // abababsplit(",") cuts the string at every comma and removes the commas. The spaces around each name stay in the pieces, which is why the map step calls trim. join(" | ") puts the new separator between elements but not before the first one or after the last one.
How split decides where to cut
split(separator, limit) takes two optional arguments. The separator can be a string or a regular expression. What it returns depends on which one you pass.
| Call | Result | Why |
|---|---|---|
| `"a,b,c".split(",")` | `["a", "b", "c"]` | Cut at each comma |
| `"a,b,c".split()` | `["a,b,c"]` | No separator: the whole string becomes one element |
| `"abc".split("")` | `["a", "b", "c"]` | Empty separator: one element per UTF-16 code unit |
| `"a,b,c".split(",", 2)` | `["a", "b"]` | Limit caps the number of elements |
| `"a,b,c".split(",", 0)` | `[]` | A limit of 0 returns an empty array |
| `"".split(",")` | `[""]` | An empty input still yields one empty piece |
| `"".split("")` | `[]` | The only case that returns an empty array without a limit |
| `"a.b.c".split(".")` | `["a", "b", "c"]` | String separators are literal, so `.` is not a regex wildcard |
Empty strings at the edges and between separators
split never drops empty pieces. A separator at the start or end of the string, or two separators next to each other, produces an empty string in the result.
console.log("a,b,,c".split(",")); // ["a", "b", "", "c"]
console.log(",a,".split(",")); // ["", "a", ""]
const text = "first line\nsecond line\n";
console.log(text.split("\n")); // ["first line", "second line", ""]The trailing newline in the last example catches people out often. Files usually end with a newline, so splitting a file into lines gives you an extra empty line at the end. If you don't want it, filter the empty pieces out or trim the string first:
const lines = "first line\nsecond line\n".trimEnd().split("\n");
console.log(lines); // ["first line", "second line"]
const tags = "a,,b,".split(",").filter(Boolean);
console.log(tags); // ["a", "b"]filter(Boolean) works because the empty string is falsy. Use it only when an empty field carries no meaning. In real tabular data an empty field is often a real value, and removing it shifts every later column.
The limit truncates; it does not keep the rest
In some other languages, a limit on split keeps the leftover text in the last element. JavaScript doesn't do that. It splits the whole string and then throws away everything past limit.
console.log("key=value=more".split("=", 2)); // ["key", "value"] ("more" is lost)If you want to split only at the first separator, use indexOf and slice:
function splitOnce(str, sep) {
const i = str.indexOf(sep);
return i === -1 ? [str] : [str.slice(0, i), str.slice(i + sep.length)];
}
console.log(splitOnce("key=value=more", "=")); // ["key", "value=more"]
console.log(splitOnce("novalue", "=")); // ["novalue"]Splitting with a regular expression
A regex separator matches a pattern instead of fixed text. The usual reason to use one is irregular whitespace or more than one kind of separator.
const messy = "one two three";
console.log(messy.split(" ")); // ["one", "", "two", "", "", "three"]
console.log(messy.split(/\s+/)); // ["one", "two", "three"]
const padded = " one two ";
console.log(padded.split(/\s+/)); // ["", "one", "two", ""]
console.log(padded.trim().split(/\s+/)); // ["one", "two"]
console.log("a;b, c|d".split(/[;,|]\s*/)); // ["a", "b", "c", "d"]
const crlf = "line1\r\nline2\nline3";
console.log(crlf.split(/\r?\n/)); // ["line1", "line2", "line3"]Leading and trailing whitespace still create empty pieces with /\s+/, so call trim first. The /\r?\n/ pattern handles both Windows (\r\n) and Unix (\n) line endings in one pass.
Capture groups appear in the output
If the regex has capturing parentheses, split puts the captured text into the result array between the pieces. This lets you keep the separators instead of discarding them.
console.log("a1b22c".split(/\d+/)); // ["a", "b", "c"]
console.log("a1b22c".split(/(\d+)/)); // ["a", "1", "b", "22", "c"]
const expr = "3+4-2";
console.log(expr.split(/([+-])/)); // ["3", "+", "4", "-", "2"]You will often get this by accident when you add parentheses only to group alternatives. Use a non-capturing group, (?:...), when you want grouping without the captured text:
console.log("a--b__c".split(/(?:--|__)/)); // ["a", "b", "c"]The g flag has no effect on split. It always splits at every match.
const s = "a\u{1F600}";
console.log(s.split("").length); // 3
console.log([...s].length); // 2How join builds the string
join(separator) turns each element into a string and puts the separator between them. If you leave out the separator, it defaults to a comma, not to an empty string.
const parts = ["2026", "11", "25"];
console.log(parts.join()); // 2026,11,25
console.log(parts.join("")); // 20261125
console.log(parts.join("-")); // 2026-11-25Elements are converted with the same rules as String(), with one exception: null and undefined become empty strings instead of "null" and "undefined". Holes in sparse arrays are also treated as empty.
console.log([1, null, undefined, "x"].join("-")); // 1---x
console.log([1, , 3].join("-")); // 1--3
console.log([[1, 2], [3]].join(";")); // 1,2;3
console.log([{ id: 1 }].join()); // [object Object]
console.log([].join(",")); // "" (empty string)Nested arrays are joined with commas because each inner array's toString calls join() with no arguments. Plain objects become "[object Object]", so map them to the text you want before joining:
const users = [{ name: "Ada" }, { name: "Linus" }];
console.log(users.map((u) => u.name).join(", ")); // Ada, LinusPutting it together: parsing a query string
This example uses everything in the chapter. It splits on &, drops empty pairs, splits each pair at its first = only, and builds an object.
function parseQuery(qs) {
return Object.fromEntries(
qs
.split("&")
.filter(Boolean)
.map((pair) => {
const i = pair.indexOf("=");
return i === -1 ? [pair, ""] : [pair.slice(0, i), pair.slice(i + 1)];
})
);
}
console.log(parseQuery("a=1&b=x=y&&c")); // { a: '1', b: 'x=y', c: '' }In production code, use URLSearchParams, which also decodes percent-encoding. The same applies to CSV. A plain split(",") breaks on quoted fields such as "Smith, John", so real CSV needs a parser.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Expecting `join()` to concatenate | `"a,b,c"` instead of `"abc"` | Pass `""` explicitly |
| Splitting text that ends with a separator | Extra `""` at the end | `trimEnd()` first, or `filter(Boolean)` |
| Splitting on `" "` with uneven spacing | Empty strings between words | `trim().split(/\s+/)` |
| Using `limit` to split once | Tail of the string disappears | `indexOf` plus `slice` |
| Capturing group in the separator regex | Separators show up in the result | Use `(?:...)` |
| `split("")` on emoji text | Broken surrogate halves | `[...str]` |
Exercise
What does " red, green ,,blue ".split(",").map((s) => s.trim()) return, and how would you change it to return only the three color names?
Show answer
It returns ["red", "green", "", "blue"]. The ",," produces an empty piece, which trims to "". Add .filter(Boolean) after the map: " red, green ,,blue ".split(",").map((s) => s.trim()).filter(Boolean) returns ["red", "green", "blue"].
Exercise
Predict the output of "10:30:45".split(":", 2), "x1y2z".split(/(\d)/), and ["a", undefined, "b"].join().
Show answer
"10:30:45".split(":", 2) returns ["10", "30"] because the limit drops the rest. "x1y2z".split(/(\d)/) returns ["x", "1", "y", "2", "z"] because captured digits are included in the result. ["a", undefined, "b"].join() returns "a,,b" because the default separator is a comma and undefined becomes an empty string.
Exercise
Write a function titleWords(str) that collapses any run of whitespace, capitalizes the first letter of each word, and returns the words joined by single spaces. titleWords(" hello big\tworld ") should return "Hello Big World".
Show answer
function titleWords(str) { return str.trim().split(/\s+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join(" "); } The trim removes the edge whitespace, split(/\s+/) handles spaces and tabs together, and filter(Boolean) protects against an all-whitespace input, where split returns [""] and w[0] would be undefined.