# How to use String replaceAll() method in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Oct 23, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-string-replaceall

> Learn how to use the replaceAll() method to replace all occurrences of a value in a string. 

The `replaceAll()` method replaces all occurrences of the search string with the replacement text and returns a new string. This method does not change the original string.

Like the [`replace()`](https://attacomsian.com/blog/javascript-string-replace) method, you can pass a string or a [regular expression](https://attacomsian.com/blog/javascript-regular-expressions) as a search pattern. The replacement can be a string or a function called for each match.

```javascript
const str = 'Mr. Red owns a red bike and a red car.'
const newStr = str.replaceAll(/red/gi, 'blue')

console.log(newStr)
// Mr. blue owns a blue bike and a blue car.
```

Note that A `RegExp` without the global (`g`) modifier will throw a `TypeError`: "replaceAll must be called with a global RegExp".

The `replaceAll()` method also accepts a function (instead of a string) as the second parameter:

```javascript
const str = 'Mr. Red owns a red bike and a red car.'
const newStr = str.replace(/red/gi, match => {
  return match.toLowerCase()
})

console.log(newStr)
// Mr. red owns a red bike and a red car.
```
