Borislav Hadzhiev
Tue Nov 02 2021·2 min read
Photo by Esther Ann
Use the replaceAll()
method to replace all commas with dots, e.g.
str.replaceAll(',', '.')
. The replaceAll
method returns a new string where
all the matches are replaced by the provided replacement.
const str1 = '123,456,789'; // ✅ Replace ALL Commas with Dots const replaced1 = str1.replaceAll(',', '.'); console.log(replaced1); // 👉️ 123.456.789 // ✅ Replace FIRST comma with Dot const replaced2 = str1.replace(/,/, '.'); console.log(replaced2); // 👉️ 123.456,789 // ✅ Replace ALL commas with Dot using Regex const replaced3 = str1.replace(/,/g, '.'); console.log(replaced3); // 👉️ 123.456.789
The first example uses the String.replaceAll method to replace all commas in a string with a dot.
The 2 parameters we passed to the replaceAll
method are:
The replaceAll
method returns a new string where all of the matches are
replaced by the provided replacement.
replaceAll
method does not change the original string, it returns a new string. Strings are immutable in JavaScript.The second example uses the String.replace method to replace the first occurrence of a comma in a string with a dot.
const str1 = '123,456,789'; // ✅ Replace FIRST comma with Dot const replaced2 = str1.replace(/,/, '.'); console.log(replaced2); // 👉️ 123.456,789
The first parameter we passed to the replace
method is a regular expression.
/ /
mark the beginning and end of the regular expression.All we try to match in our regular expression is a single comma.
By default the replace
method replaces the first occurrence of the matched
regular expression with the provided replacement string.
An alternative to the replaceAll
method is to use the replace
method with
the g
(global) flag.
To replace all commas with dots, call the replace()
method with the
following regular expression /,/g
, e.g. str.replace(/,/g, '.')
. The
replace
method will return a new string with all commas replaced by dots.
const str1 = '123,456,789'; // ✅ Replace ALL commas with Dot using Regex const replaced3 = str1.replace(/,/g, '.'); console.log(replaced3); // 👉️ 123.456.789
We used the g
(global) flag because we want to match all occurrences of a
comma in the string and not just the first occurrence.
replaceAll
method, however thereplaceAll
method is not supported by Internet Explorer, whereas the replace
method is.My personal approach is to always use the replaceAll
method where possible,
because not all developers are familiar with regular expressions.
If you ever need help reading a regular expression, bookmark this regex cheatsheet from MDN. It's by far the best one out there.