# How to replace a character in a string using JavaScript

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

> Learn how to use the replace() method to replace a specific character inside a string using JavaScript.

You can use the [`replace()`](https://attacomsian.com/blog/javascript-string-replace) method to replace the occurrence of a character inside a string in JavaScript.

Here is an example that replaces a character in a string with another character using the `replace()` method:

```javascript
const str = 'Hello World!'

const updated = str.replace('l', '!')

console.log(updated)
// He!lo World!
```

By default, the `replace()` will only replace the first occurrence of the specified character. 

To replace all occurrences of a specified character, you must use a [regular expression](https://attacomsian.com/blog/javascript-regular-expressions#regular-expression-modifiers) with the global modifier (`g`):

```javascript
const str = 'Hello World!'

const updated = str.replace(/l/g, '!')

console.log(updated)
// He!!o Wor!d!
```

For a global case-insensitive replacement, you can combine the global modifier (`g`) with the ignore case modifier (`i`):

```javascript
const str = 'HeLLo World!'

const updated = str.replace(/l/gi, '!')

console.log(updated)
// He!!o Wor!d!
```

Alternatively, you could use the `replaceAll()` method to replace all occurrences of a character inside a string: 

```javascript
const str = 'HelLo World!'

const updated = str.replaceAll(/l/gi, '!')

console.log(updated)
// He!!o Wor!d!
```

The `replaceAll()` method was introduced in ES2021. It replaces all occurrences of the search string with the replacement text and returns a new string.
