How to Remove all dots from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Sep 7, 2022

banner

Photo from Unsplash

Remove all dots from a String #

To remove all dots from a string:

  1. Call the replaceAll method, passing it a dot as the first parameter and an empty string as the second - str.replaceAll('.', '').
  2. The replaceAll method returns a new string with all matches replaced by the provided replacement.
index.js
const str = 'a.b.c.'; const dotsRemoved = str.replaceAll('.', ''); console.log(dotsRemoved); // 👉️ 'a_b_c'

We passed the following parameters to the String.replaceAll method:

  1. The character we want to replace in the string>
  2. The replacement for each match.
We used an empty string for the replacement because we want to remove all dots from the string.

The replaceAll() method doesn't change the contents of the original string, it returns a new string with all matches replaced.

Alternatively, you can use the String.replace() method.

Remove all dots from a String using String.replace() #

Use the String.replace() method to remove all dots from a string, e.g. const dotsRemoved = str.replace(/\./g, '');. The replace() method will remove all dots from the string by replacing them with empty strings.

index.js
const str = 'a.b.c.'; const dotsRemoved = str.replace(/\./g, ''); console.log(dotsRemoved); // 👉️ 'abc'

We passed the following parameters to the String.replace method:

  1. A regular expression that matches all dots in the string.
  2. The replacement for each match.

The forward slashes / / mark the beginning and end of the regular expression.

We prefixed the dot with a backslash to escape it.

The dot . has a special meaning in regular expressions, but we need to match a literal dot ..

We used the g (global) flag to match all occurrences of dots in the string and not just the first occurrence.

By replacing all dots with an empty string, we remove all dots from the string.

The replace method doesn't change the original string, it returns a new string with the matches replaced. Strings are immutable in JavaScript.

Which approach you pick is a matter of personal preference. I'd go with the replaceAll() method to avoid using a regular expression.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.