Replace vs Replace All
Replace all occurrences in a string without RegEx

I have been a full-stack developer for twelve years and am currently part of the Cloud FinOps team at Atlassian. I previously ran an App development agency, managing various teams across design and development, leading web, backend and native mobile app developers in Australia and Europe. My strengths are system architecture design and communicating complicated tech to everyday people. Having helped scale tech at numerous startups, I am passionate about making a positive difference. When not working, you can find me writing tech articles and teaching Javascript and React at SheCodes, an initiative helping to get more women into tech. I regularly give talks on various topics, focusing on the impact the technology we build can have. I am devastated by the state of the world, love a good political rant and can often be swearing at no one in particular. I enjoy building things in JavaScript, Deno and Node.
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.



