brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: replaceAll() replaces every match without a regex

Web-Development
~/tips/tip-javascript-string-replaceall

"192.168.1.10".replaceAll(".", "-");

Replaces every occurrence of a string in one call, with no regex escaping.

For years the answer to “replace all occurrences in a string” was str.replace(/x/g, y), and then escaping the search text when it contained a dot or a bracket. replaceAll() takes a plain string and replaces every match. I think it should have existed from day one.

A string pattern is matched literally, so special characters need no escaping:

"192.168.1.10".replaceAll(".", "-");
// "192-168-1-10"

"A hacker called ha.*er".replaceAll("ha.*er", "[REDACTED]");
// "A hacker called [REDACTED]"

With replace() and a string, only the first match changes, and that is the bug replaceAll() removes. With a plain .replace(".", "-") you would get 192-168.1.10.

You can still pass a regex when you need a pattern, but it must have the g flag or the call throws:

"aabbcc".replaceAll(/b/g, ".");  // "aa..cc"
"aabbcc".replaceAll(/b/, ".");   // TypeError

The replacement can be a function, called once per match, and special patterns such as $& (the matched text) work like they do in replace():

"a1b2".replaceAll(/\d/g, (m) => m * 10);  // "a10b20"
"a-b".replaceAll(/\w/g, "[$&]");        // "[a]-[b]"

Two caveats. The original string is never changed, so assign the result. And an empty search string inserts the replacement between every character: "xxx".replaceAll("", "_") gives "_x_x_x_", which surprises people when a variable happens to be empty.

It works in all major browsers since August 2020 and in current Node versions.

Further reading: MDN: String.prototype.replaceAll()

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link