# How to replace all occurrences of a string in JavaScript

> Learn how to replace all occurrences of a string in JavaScript, using a global regex with the g flag and the i flag for case, or chaining split() and join().

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2018-07-02 | Updated: 2019-09-29 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/how-to-replace-all-occurrences-string-javascript/

## Using a regular expression

This simple regex will do the task:

```js
String.replace(/<TERM>/g, '')
```

This performs a **case sensitive** substitution.

(You can test your pattern against sample text in my [regex tester](https://flaviocopes.com/tools/regex-tester/) before using it.)

Here is an example, where I substitute all occurrences of the word 'dog' in the string `phrase`:

```js
const phrase = 'I love my dog! Dogs are great'
const stripped = phrase.replace(/dog/g, '')

stripped //"I love my ! Dogs are great"
```

To perform a case insensitive replacement, use the `i` option in the regex:

```js
String.replace(/<TERM>/gi, '')
```

Example:

```js
const phrase = 'I love my dog! Dogs are great'
const stripped = phrase.replace(/dog/gi, '')

stripped //"I love my ! s are great"
```

Remember that if the string contains some special characters, it won't play well with regular expressions, so the suggestion is to escape the string using this function (taken from [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters)):

```js
const escapeRegExp = (string) => {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
```

## Using split and join

An alternative solution, albeit slower than the regex, is using two [JavaScript](https://flaviocopes.com/javascript/) functions.

The first is `split()`, which truncates a string when it finds a pattern (case sensitive), and returns an array with the tokens:

```js
const phrase = 'I love my dog! Dogs are great'
const tokens = phrase.split('dog')

tokens //["I love my ", "! Dogs are great"]
```

Then you join the tokens in a new string, this time without any separator:

```js
const stripped = tokens.join('') //"I love my ! Dogs are great"
```

Wrapping up:

```js
const phrase = 'I love my dog! Dogs are great'
const stripped = phrase.split('dog').join('')
```
