How to Replace all Occurrences of a String in JavaScript

Replace all Occurrences of a String in JavaScript

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

NameTypeDescription
findstringThe value to find in a string.
replacestringThe 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

NameTypeDescription
regexFindstringThe value to find in a string. Can be a regular expression.
replacestringThe 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:

Leave a Reply

Your email address will not be published. Required fields are marked *