0
0
JavascriptHow-ToBeginner · 3 min read

How to Use replaceAll in JavaScript: Syntax and Examples

In JavaScript, use replaceAll() to replace every occurrence of a substring or pattern in a string with a new string. It takes two arguments: the substring or regular expression to find, and the replacement string. This method returns a new string without changing the original.
📐

Syntax

The replaceAll() method has this syntax:

  • string.replaceAll(searchValue, replaceValue)

searchValue: The substring or global regular expression to find in the string.

replaceValue: The string to replace each match with.

This method returns a new string with all matches replaced.

javascript
const newString = originalString.replaceAll(searchValue, replaceValue);
💻

Example

This example shows how to replace all spaces with dashes in a sentence.

javascript
const sentence = "I love JavaScript programming.";
const result = sentence.replaceAll(" ", "-");
console.log(result);
Output
I-love-JavaScript-programming.
⚠️

Common Pitfalls

One common mistake is using replace() instead of replaceAll(), which only replaces the first match. Another is passing a string to replaceAll() when you want to replace patterns with regular expressions; in that case, use a global regular expression.

javascript
const text = "apple apple apple";

// Wrong: only replaces first 'apple'
const wrong = text.replace("apple", "orange");
console.log(wrong); // orange apple apple

// Right: replaces all 'apple'
const right = text.replaceAll("apple", "orange");
console.log(right); // orange orange orange
Output
orange apple apple orange orange orange
📊

Quick Reference

ParameterDescription
searchValueString or global RegExp to find all matches
replaceValueString to replace each match
ReturnsNew string with all matches replaced

Key Takeaways

Use replaceAll() to replace every occurrence of a substring or pattern in a string.
replaceAll() returns a new string and does not change the original string.
To replace patterns, use a global regular expression with replaceAll().
Avoid using replace() when you want to replace all matches, as it only replaces the first.
replaceAll() is supported in modern JavaScript environments (ES2021 and later).