Strings
replace() and replaceAll()
Swap a piece of a string for another — the first one or all of them.
Why it exists
Data almost always needs "cleaning up" or reformatting: removing spaces from a phone number, swapping a comma for a dot in "12,5", putting a name into an email template, hiding a rude word. Without replace you'd have to find the position, cut the string and glue it back. replaceAll does it in one line — for every occurrence at once.
Where it's used
- Cleaning input:
phone.replaceAll(" ", ""),card.replaceAll("-", ""). - Numbers from a form:
"12,5".replace(",", ".")beforeNumber(...). - Templates:
"Hi, {name}!".replace("{name}", user.name). - Word filters in comments, highlighting found text.
Syntax
string.replace(what, replacement)
string.replaceAll(what, replacement)Examples
"cat and cat".replace("cat", "dog"); // → "dog and cat"
"cat and cat".replaceAll("cat", "dog"); // → "dog and dog"const phone = "+1 555 123-4567";
phone.replaceAll(" ", "").replaceAll("-", ""); // → "+15551234567"const input = "12,5";
Number(input); // → NaN
Number(input.replace(",", ".")); // → 12.5"a b c".replace(/\s+/g, "-"); // → "a-b-c"Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
replace with a string as the first argument changes only the first occurrence — that's how it has worked since the language began. To replace all of them, people used a regular expression with the g flag: replace(/cat/g, "dog"), and in 2021 the clearer replaceAll arrived.
Replacing with an empty string "" means deleting: replaceAll(" ", "") removes every space.
The first argument can be a regular expression — a search pattern: /\s+/g means "one or more whitespace characters in a row". It's powerful, but a mini-language of its own.
Both methods return a new string — strings are immutable.
Traps
How it differs from…
split()andjoin()split(x).join(y)is the old way to replace every occurrence, from beforereplaceAllexisted. Existing code is still full of it.
When to pick something else
Don't build HTML or SQL with replace and user data: that's how vulnerabilities appear (XSS, SQL injection). Template engines and parameterized queries exist for that. And for edge spaces only, trim() is simpler.
Practice
Lessons where this appears
- Byte starts a newspaperTale · Chapter 6 · Strings
- The Gazette newsroomWorkshop · Chapter 6 · Strings
- The TypoBoss · Chapter 6 · Strings
- The detective searches by descriptionTale · Chapter 7 · Regular expressions
- Why do regexes look like line noise?Why? · Chapter 7 · Regular expressions
- The cat cafe receiptLab · Chapter 24 · Modules: import and export