How to replace a character in a string using JavaScript

You can use the 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:

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 with the global modifier (g):

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):

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:

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.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.