Borislav Hadzhiev
Tue Oct 12 2021·3 min read
Photo by Sam Manns
To replace all dots in a string:
replaceAll()
method, passing it a dot as the first parameter and a
replacement string as the second.replaceAll
method returns a new string with all matches replaced by the
provided replacement.const str = 'a.b.c'; const withoutDots = str.replaceAll('.', '-'); console.log(withoutDots); // 👉️ 'a-b-c'
We pass the following parameters to the String.replaceAll method:
-
,
however you could use whatever replacement string you need, e.g. a whitespace
character ' '
.replaceAll
method is not supported in Internet Explorer versions 6-11. If you need to support the browser use one of the other approaches covered in this article.To replace all dots in a string:
replace()
method, passing it a regular expression that matches all
dots as the first parameter and the replacement character as the second.replace
method will return a new string with all dot characters
replaced.const str = 'a.b.c'; const withoutDots = str.replace(/\./g, '_'); console.log(withoutDots); // 👉️ 'a_b_c'
We passed the following parameters to the String.replace method:
The \
character, before the dot is used to escape special characters. The .
character has a special meaning in
regular expressions
and matches one or more characters of any type.
We want the dot to be taken literally, so we escape it.
We use the g
(global) flag because we want to match all occurrences of the
dot character in the string, and not just the first one.
replace
method does not change the contents of the original string, it returns a new string with the matches replaced.If you're looking to avoid regular expressions, and you need to support Internet Explore, you can use the next approach.
To replace all dots in a string:
split()
method to split the string on each dot character. The
split
method returns an array containing the divided substrings.join()
method on the array, passing it a replacement character for
the dots. The join
method returns a new string by concatenating the array
elements with the provided separator.const str = 'a.b.c'; const withoutDots = str.split('.').join('_'); console.log(withoutDots); // 👉️ 'a_b_c'
The String.split method splits the string on each dot character.
const str = 'a.b.c'; const split = str.split('.'); console.log(split); // 👉️ ['a', 'b', 'c']
The final step is to join all array elements with a separator (replacement for each dot).
replaceAll
method, but it gets the job done if you have to support Internet Explorer and don't want to use regular expressions.