- Published on
Dive into `string.prototype.replaceAll`
- Authors

- Name
- hwahyeon
string.prototype.replaceAll is a method that changes all occurrences of a specific string in a sentence to a new one. It is similar to the replace method, but replace only changes the first occurrence of the specified string, not all of them.
Usage
str.replaceAll(searchValue, replaceValue)
searchValue: The string or regular expression to search for.replaceValue: The new string to replace the matched value with.
Example
const originalStr = 'Hello world! Hello Germany!'
const newStr = originalStr.replaceAll('Hello', 'Hi')
console.log(newStr) // "Hi world! Hi Germany!"
In the original sentence, every occurrence of "Hello" was changed to "Hi."
Similarity with Python's str.replace()
The replaceAll() method is very similar to Python's str.replace() method:
original_str = "Hello world! Hello Germany!"
new_str = original_str.replace("Hello", "Hi")
print(new_str) # "Hi world! Hi Germany!"
Cautions
With old browsers
The replaceAll() method is a relatively recent addition to JavaScript, so older browsers may not support it. According to the "Can I Use" website, Internet Explorer does not provide support for it.
With regular expression
If you want to use this method with a regular expression, you must use the global flag (g), otherwise, the replaceAll() method will throw an error. The global flag ensures that every match is found, because by default, a regular expression only finds the first match.
Without the g Flag (Error)
const text = 'Hello hello Hello'
const result = text.replaceAll(/Hello/, 'Hi')
// TypeError: replaceAll called with a non-global RegExp
With the replace() Method (First Match Only)
const text = 'Hello hello Hello'
const result = text.replace(/Hello/, 'Hi')
console.log(result)
// "Hi hello Hello" (only the first match is replaced)
With the g Flag (All Matches Replaced)
const text = 'Hello hello Hello'
const result = text.replaceAll(/Hello/g, 'Hi')
console.log(result)
// "Hi hello Hi"