Replace all occurrences in a string – Javascript

To replace all the occurrences in a string in Javascript, we will use the following method.

For example, you have the following string variable.

let string = "adnan_tech_com"

And you want to replace all underscores with a white space.

You can use the following code to replace all occurrences of underscores with a whitespace.

string = string.split("_").join(" ") // adnan tech com

Explanation

First, you need to split the string by underscore. It will return an array.

let string = "adnan_tech_com"

string = string.split("_") // ["adnan", "tech", "com"]

Then we can join the array by whitespace.

let string = "adnan_tech_com"

string = string.split("_")

string = string.join(" ") // adnan tech com

Don’t use replace()

You should not use “replace” function because it will replace only the first occurrence in a string.

let string = "adnan_tech_com"

string = string.replace("_", " ") // adnan tech_com

Checkout our more tutorials on Javascript.