How to Remove all dots from a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 12 20212 min read

banner

Photo by Nathan Dumlao

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 pass the following parameters to the String.replaceAll method:

  1. The character we want to match in the string
  2. The replacement for each match
The replacement in our case is an empty string, because we want to remove all dots in the string.

The replaceAll method does not change the contents of the original string, it returns a new string with all matches replaced.

The replaceAll method is not supported in Internet Explorer versions 6-11. If you need to support the browser use the next approach covered in this article.

To remove all dots from a string:

  1. Call the replace method, passing it a regular expression that matches all dots as the first parameter and an empty string as the second.
  2. The replace method will return a new string with all dots replaced by an empty string.
index.js
const str = 'a.b.c.'; const dotsRemoved = str.replace(/\./g, ''); console.log(dotsRemoved); // ๐Ÿ‘‰๏ธ 'abc'

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

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

We have to prefix the dot in the regular expression with a \ character, because we need to escape it.

The dot . is a special character in regular expressions, but we need to match a literal dot ., so we escape it.

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

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

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee