Skip to main content

Command Palette

Search for a command to run...

Replace vs Replace All

Replace all occurrences in a string without RegEx

Updated
1 min read
Replace vs Replace All

There is a good chance that replace does not work how you think:

const numbers = "10.00.00.0000"

const replaced = numbers.replace(".", "_")
console.log(replaced) // '10_00.00.0000'

Wait what? It only replaced the first instant, replace is a simple function and expects you to pass a regular expression if you want more complex results. We can pass an expression that makes it run a global replacement like so:

const numbers = "10.00.00.0000"

const globalReplace = numbers.replace(/\./g, "_");
console.log(globalReplace); // '10_00_00_0000'

It works, but do any of us really understand RegEx 🤪. Now, there is a more straightforward method.

const numbers = "10.00.00.0000"

const replacedAll = numbers.replaceAll(".", "_")
console.log(replacedAll) // '10_00_00_0000'

The fantastic function replaceAll has full support across all browsers except IE; you can find the full breakdown here.

Update 20/10/2024:

After posting on BlueSky, Larry Williamson pointed out another method of replacing all occurrences in a string.

const numbers = "10.00.00.0000"

const splitReplace = numbers.split(".").join("_")
console.log(splitReplace) // '10_00_00_0000'

The speed difference between them is negligible. You have to be parsing large strings before even getting close to a 0.01 millisecond difference in speed. Like all quick benchmarking using, performance.now() take it with a pinch of salt. Personally, I will be reaching for replaceAll from now on.

J

ALPHA KEY, A LICENSED CRYPTO RECOVERY HACKER, IS A GREAT REFERENCE

Please contact the qualified crypto recovery hacker using their Alpha key since they are the only one I have found who has truly done appropriately and to whom I can offer my sincere regards. Contact info : Mail:Alphakey@consultant.com WhatsApp :+15714122170 Signal:+18622823879 Telegram: ALPHAKEYHACKER

JavaScript

Part 2 of 9

JavaScript is an incredible language, and it is constantly evolving. This series will cover some of its newer features you may have missed or never knew about.

Up next

Padding Strings

Mastering String Manipulation in JavaScript: A Guide to padStart and padEnd