Borislav Hadzhiev
Tue Oct 12 2021·2 min read
Photo by Nathan Dumlao
To remove all dots from a string:
replaceAll
method, passing it a dot as the first parameter and an
empty string as the second - str.replaceAll('.', '')
.replaceAll
method 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 pass the following parameters to the String.replaceAll method:
The replaceAll
method does not change the contents of the original string, it
returns a new string with all matches replaced.
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:
replace
method, passing it a regular expression that matches all
dots as the first parameter and an empty string as the second.replace
method will return a new string with all dots replaced by an
empty string.const str = 'a.b.c.'; const dotsRemoved = str.replace(/\./g, ''); console.log(dotsRemoved); // 👉️ 'abc'
We pass the following parameters to the String.replace method:
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.
replace
method does not change the original string, it returns a new string with the matches replaced. Strings are immutable in JavaScript.