replaceAll()
ES2021+Returns a new string with all matches of a pattern replaced by a replacement.
Syntax
string.replaceAll(searchValue, replaceValue)Parameters
searchValue string | RegExp The value to search for (must be global if RegExp)
replaceValue string | Function The replacement string or function
Return Value
A new string with all replacements made
Examples
const str = 'Hello World World';
console.log(str.replaceAll('World', 'JS')); 📌 When to Use
Use replaceAll() when you need to replace every occurrence of a substring without using regex. It provides cleaner syntax than replace() with /g flag for simple string replacements.
⚠️ Common Mistakes
Using replaceAll() with a regex without the global flag - this will throw a TypeError. Either add /g or use a string pattern.
Forgetting that replaceAll() is an ES2021 feature - older browsers and Node.js versions may not support it.
Using replaceAll() when replace() would be more efficient for complex patterns that need capturing groups or lookaheads.
✅ Best Practices
Use replaceAll() for simple literal string replacements as it is more readable and expresses intent clearly.
For older browser support, use split().join() as a polyfill: str.split(search).join(replacement).
When using replaceAll() with a regex, always ensure the global flag is set, or use replace() instead to avoid runtime errors.
⚡ Performance Notes
replaceAll() is generally as performant as replace() with /g flag. For very large strings with many replacements, split/join pattern might be slightly faster in some engines. The performance difference is usually negligible for typical use cases.
🌍 Real World Example
Data Cleaning and Text Normalization
replaceAll() excels at cleaning user input, normalizing data formats, and preparing text for storage or display without the complexity of regex.
// Clean up phone number input
function cleanPhoneNumber(phone) {
return phone
.replaceAll(' ', '')
.replaceAll('-', '')
.replaceAll('(', '')
.replaceAll(')', '');
}
console.log(cleanPhoneNumber('(010) 1234-5678'));
// Output: '01012345678'
// Normalize line endings across platforms
function normalizeLineEndings(text) {
return text
.replaceAll('\r\n', '\n') // Windows to Unix
.replaceAll('\r', '\n'); // Old Mac to Unix
}
// Escape markdown special characters
function escapeMarkdown(text) {
return text
.replaceAll('*', '\\*')
.replaceAll('_', '\\_')
.replaceAll('~', '\\~')
.replaceAll('`', '\\`')
.replaceAll('#', '\\#');
}
console.log(escapeMarkdown('Hello *world* and _universe_'));
// Output: 'Hello \*world\* and \_universe\_'
// Replace placeholder tokens in content
function fillTokens(content, tokens) {
let result = content;
for (const [key, value] of Object.entries(tokens)) {
result = result.replaceAll(`{{${key}}}`, value);
}
return result;
}
const template = 'Welcome {{user}}! Your order #{{orderId}} is ready.';
console.log(fillTokens(template, { user: 'Alice', orderId: '12345' }));
// Output: 'Welcome Alice! Your order #12345 is ready.'