In this article, you’ll learn how to replace all occurrences of a string in JavaScript with .replace()
and .replaceAll()
and the difference between them.
Replace all Occurrences of a String in JavaScript
Using String.replaceAll(str find, str replace)
The most straightforward way is using String.replaceAll(str find, str replace)
. Please note that this and the following functions only return
a new string value, not replace the old string directly.
Syntax
String.replace(str find, str replace);
Parameters
Name | Type | Description |
---|---|---|
find | string | The value to find in a string. |
replace | string | The value to replace with. |
Code
const string = "Le_Minh_ThoNg";
const new_string = string
.replaceAll("_", " ")
.replaceAll("N", " ");
console.log(new_string);
Output
"Le Minh Tho g"
Using String.replace(str regexFind, str replace)
A more specific way of replacing values. .replace()
is different from .replaceAll()
in that .replace()
accepts regular expressions (/…/)
as a value for finding. Using String.replace(str regexFind, str replace)
is also a great way to replace all occurrences of a string in JavaScript.
Another thing to note is that the finding value must have "g"
at the end if you want to search and replace all occurrences of something. Additionally by adding "i"
to the end of the regular expression it ignores case when replacing.
Syntax
String.replace(str regexFind, str replace);
Parameters
Name | Type | Description |
regexFind | string | The value to find in a string. Can be a regular expression. |
replace | string | The value to replace with. |
Code
const string = "Le_Minh_ThoNg";
const _string = string
.replace(/_/g, " ")
.replace(/n/ig, " ");
console.log(_string);
Output
"Le Mi h Tho g"
It’s even possible to replace every alphabetical letter or number with the use of regexes in regular expressions. Here are some examples.
Code
const string = "A12Bc34";
console.log(string.replace(/[a-z]/g," "));
console.log(string.replace(/[A-Z]/g," "));
console.log(string.replace(/[1-9]/g," "));
console.log(string.replace(/[a-z]/gi," "));
Output
"A12B 34"
" 12 c34"
"A Bc "
" 12 34"
There are more things you can do with regular expressions, though there’s too much to cover here.
Summary
To replace all occurrences of a string in JavaScript, you use either .replace()
or .replaceAll()
, the former for more precise replacements and the latter for more straightforward replacements. You can learn more about Javascript strings here.
Maybe you are interested:
- Convert a String to Title Case in JavaScript
- How to compare Strings in JavaScript
- Remove all Line Breaks from a String in JavaScript

Hello, my name is Davis Cole. I love learning and sharing knowledge about programming languages. Some of my strengths are Java, HTML, CSS, JavaScript, C#,… I believe my articles about them will help you a lot.
Programming Languages: Java, HTML, CSS, JavaScript, C#, ASP.NET, SQL, PHP