Last updated: Sep 7, 2022
Photo from Unsplash
To remove all dots from a string:
replaceAllmethod, passing it a dot as the first parameter and an empty string as the second -
replaceAllmethod returns a new string with all matches replaced by the provided replacement.
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:
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 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.
const str = 'a.b.c.'; const dotsRemoved = str.replace(/\./g, ''); console.log(dotsRemoved); // 👉️ 'abc'
We passed the following parameters to the String.replace method:
The forward slashes
/ / mark the beginning and end of the regular expression.
We prefixed the dot with a backslash to escape it.
. has a special meaning in
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.
Which approach you pick is a matter of personal preference. I'd go with the
replaceAll() method to avoid using a regular expression.