Explain Codes LogoExplain Codes Logo

How to replace all dots in a string using JavaScript

javascript
regex
string-manipulation
javascript-functions
Anton ShumikhinbyAnton Shumikhin·Oct 6, 2024
TLDR

Quick way to replace all dots in a string using JavaScript is through the replace() method with a regex pattern /\./g. Like good old magic:

let myAwesomeString = "example.com".replace(/\./g, "-");

In the great words of Bob Ross, we've just made a happy little accident: myAwesomeString becomes "example-com". That magic talisman /\./g scopes all occurrences of dots, and turns them into dashes.

What's that backslash doing before the dot?

The dot, as innocent as it seems, holds special power in regex. Used alone, it matches any character. So, to pin it down and talk about the actual dot, not just anybody, we have to precede it with a backslash. Like this \. - targeted dot, not a wild card anymore.

Why should I care about the /g flag?

You cruised through with /g, the global pirate flag in /\./g. She bellows to replace all appearances of the dot on the high seas of the string, not only the first encountered. Without /g our mighty dot-dashing endeavor would stop after the first dot. Not what we want, aye?

The readable alternative: split and join

When regex seems like deciphering hieroglyphs, use the simple folks: .split('.') and .join(' '). Like two peas in a pod:

let myAwesomeString = "example.com".split('.').join(' ');

This combo move splits the string at each dot into an array. It then joins them back into a single string, placing a space where every dot used to live. Not all heroes wear capes.

Meet the flexible friend - new RegExp

Using new RegExp lets us create dynamic regex patterns when we don't know our enemy until runtime. It's like a spy who can adopt different identities:

let sneakyDot = "."; let undercoverRegex = new RegExp(sneakyDot.replace(/\./g, "\\."), "g"); let myAwesomeString = "example.com".replace(undercoverRegex, '-');

Now, we've got a regex in disguise, ready to fulfil its mission: flush out all literal dots and replace them with dashes. Spy-level stuff, right?

Execution on diverse terrain: testing various strings

Before our hardworking code goes live, strap it to a test bench with variously tricky input strings. Strings with escaped dots, consecutive dots, or ones lacking any dots can be test driving tracks you may want to consider. Make sure your code is a skilled driver!

The custom-made solution: replaceAll

Despite how mighty replace() with regex can be, having a custom replaceAll() function increases code-readability for those less in-the-know about regex:

function replaceAll(string, search, replace) { return string.split(search).join(replace); } let myAwesomeString = replaceAll("example.com", ".", " ");

If all else fails, go custom!cout << " 😎" << endl;

External powerhouse: string-replacement libraries

For projects with more replacement needs and complex regex patterns, consider libraries like str-replace. They boost efficiency, come in as life-savers, and prevent common regex mishaps from stealing your thunder.

Safeguarding special characters

Regex has special characters that wear various hats, like the dot. *, +, ?, [, ], (, ), {, }, \, ^, $, and | all have distinct roles. Always remember to escape them using \ when they're just meant to chill in the string.