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.