Overview
The replaceAll()
method in JavaScript is a powerful tool for string manipulation, allowing developers to replace all occurrences of a substring within a given string with another substring. This method is relatively new, having been introduced in ECMAScript 2021 (ES12). Prior to its introduction, achieving the same result required either complex regular expressions or looping constructs.
What is replaceAll() Used For?
The primary use of the replaceAll()
method is to find all instances of a specific substring in a string and replace them with a different substring. This is especially useful in text processing, data cleaning, or any scenario where consistent replacement throughout a string is required.
Syntax, Parameters, and Return Value
Syntax:
str.replaceAll(searchValue, newValue)
Parameters:
searchValue
– The substring to be replaced. Can be a string or a global RegExp.newValue
– The string to replace each match. Can also be a function that returns the replacement string.
Return Value:
A new string, with all matches of the searchValue replaced by newValue.
Code Examples
Basic Replacement
This example demonstrates replacing all instances of ‘dog’ with ‘cat’ in a sentence.
const sentence = 'The quick brown dog jumps over the lazy dog.';
const newSentence = sentence.replaceAll('dog', 'cat');
console.log(newSentence);
// Output: The quick brown cat jumps over the lazy cat.
Using a Function as newValue
This example shows how to dynamically generate the replacement string for each match using a function.
const message = 'I owe you 30 dollars and 45 dollars.';
const updatedMessage = message.replaceAll(/\d+/g, (match) => `${parseInt(match, 10) * 1.1}`);
console.log(updatedMessage);
// Output: I owe you 33 dollars and 49.5 dollars.
Conclusion
The replaceAll()
method is a significant addition to the JavaScript language, simplifying the task of replacing substrings throughout a string. Its introduction in ECMAScript 2021 has filled a notable gap in the language’s string manipulation capabilities, making certain tasks more straightforward and cleaner to implement. As we’ve seen through examples, whether you’re dealing with simple string replacements or need to use a function for a dynamic replacement, replaceAll()
elegantly addresses these needs.