Borislav Hadzhiev
Fri Oct 29 2021·2 min read
Photo by Kevin Laminto
Use the replaceAll()
method to replace all commas in a string, e.g.
str.replaceAll(',', ' ')
. The replaceAll
method takes a substring and a
replacement as parameter and returns a new string with all matches replaced by
the provided replacement.
const str = 'a,long,string'; const commasReplaced = str.replaceAll(',', ' '); console.log(commasReplaced); // 👉️ a long string
We passed the following parameters to the String.replaceAll method:
,
const str = 'a,long,string'; const commasReplaced = str.replaceAll(',', '_'); console.log(commasReplaced); // 👉️ a_long_string
Note that the replaceAll
method does not change the original string, it
returns a new string with all matches replaced by the provided replacement.
replaceAll
method is not supported in Internet Explorer versions 6-11. If you need to support the browser, use the replace
method instead.Use the replace()
method to replace all commas in a string, e.g.
str.replace(/,/g, ' ')
. The method takes a regular expression and a
replacement string as parameters and returns a new string with the matches
replaced by the provided replacement.
const str = 'a,long,string'; const commasReplaced = str.replace(/,/g, ' ') console.log(commasReplaced) // 👉️ a long string
We passed the following parameters to the String.replace method:
We used the g
(global) flag because we want to match all commas in the string
and not just the first occurrence.
In the example we replaced each comma with a space, however you can provide a replacement string that suites your use case.
replace
method does not mutate the original string, it returns a new string. Strings are immutable in JavaScript.The replaceAll
method is quite a bit easier to read than replace
, however if
you have to support Internet Explorer, replace
gets the job done.