String. prototype. replaceAll()
Returns a new string in which every occurrence of a pattern has been replaced with the given text or the result of a function.
- Returns
- A new string with every match replaced by the replacement text.
- Changes the original
- No
Example
#const slug = 'javascript course for beginners'.replaceAll(' ', '-')
const template = 'Hi {name}! {name}, you have a new task.'
console.log(slug)
console.log(template.replaceAll('{name}', 'Mia'))Definition and usage
#The replaceAll() method works like replace(), but it always replaces every match, not just the first one. With plain text, you don't need to build a regular expression with the g flag or worry about special characters.
The pattern can be a string or a regular expression, but the expression must have the g flag. Without it, the method throws a TypeError. The second argument, just like in replace(), can be text (with $&, $1 sequences) or a function.
Like all string methods, replaceAll() does not change the original, it just returns a new string.
Syntax
#string.replaceAll(pattern, replacement)Parameters
#pattern
string | RegExp
A string, or a regular expression with thegflag. Every occurrence gets replaced.replacement
string | function
The replacement text, or a function called for every match whose result ends up in the new string.
More examples
#const version = 'v1.2.3'
console.log(version.replaceAll('.', '-'))
console.log(version.replace(/./g, '-'))In a regular expression, a dot means any character, so /./g replaced everything. replaceAll() with a string treats the dot literally.
const text = 'a-b-c'
console.log(text.replaceAll(/-/g, ' + '))
try {
text.replaceAll(/-/, ' + ')
} catch (error) {
console.log(error.name)
}const text = 'Learning html, css, and javascript'
const loud = text.replaceAll(/html|css|javascript/g, (tech) => tech.toUpperCase())
console.log(loud)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- For replacing plain text,
replaceAll()is the simplest and most readable choice. Reach for a regular expression when you need a pattern, such as any digit. - Remember the
gflag with a regular expression. Without it, you get aTypeErrorinstead of a result.
Related entries
#- String.prototype.replace()Returns a new string in which the first match of a pattern (or all matches, with the g flag) has been replaced with other text.
- String.prototype.split()Splits a string into an array of pieces based on a separator: a character, a string, or a regular expression.
- RegExpA regular expression: a pattern for searching, validating, and replacing pieces of text.
- Array.prototype.join()Joins the array’s elements into a single string with a chosen separator.
Spotted a mistake or missing an example? Write to us.