Skip to main content
0 reactions

How to Replace Every Match in a String with replaceAll() in JavaScript

Card titled replaceAll() in JavaScript, labelled JavaScript basics, with three ticked lines: the string Sync A/B/C, replaceAll of a slash with a dash, and the result Sync A-B-C.

replaceAll() finds every place a piece of text appears in a string and replaces it, such as every / with -. It gives you a new string and leaves the original as it was.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
text.replaceAll(pattern, replacement)
  • text: the string to look in.
  • pattern: the text to find, such as '/'.
  • replacement: the text to put in its place, such as '-'.
  • The result is a new string. text itself doesn’t change.

See String.prototype.replaceAll() (opens in a new tab) on MDN.

Prerequisites

The Example

A name with two slashes, changed with replaceAll() and with replace(), in a file named names.js.

Step 1: Write the Code

names.jsJavaScript
const name = 'Sync A/B/C';

console.log(name.replaceAll('/', '-'));
console.log(name.replace('/', '-'));
console.log(name);

Step 2: Run It

TerminalBash
node names.js
OutputPlain text
Sync A-B-C
Sync A-B/C
Sync A/B/C
  • replaceAll() replaced both slashes.
  • replace() replaced only the first one.
  • name still has its slashes: neither method changed it.

Common Mistakes

MistakeWhat happensDo this instead
Using replace() to change every matchOnly the first match changesUse replaceAll()
Expecting name.replaceAll('/', '-') to change namename keeps its slashesKeep the result: const safeName = name.replaceAll('/', '-');

FAQ

Does replaceAll() change the original string?

No. Strings in JavaScript don’t change; replaceAll() gives back a new one, as the last line of the output shows.

Conclusion

Use replaceAll() when every match should change, and keep its result, because the original string stays as it was.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments