To replace all the occurrences in a string in Javascript, we will use the following method.
For example, you have the following string variable.
1 | 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.
1 | string = string.split( "_" ).join( " " ) // adnan tech com |
Explanation
First, you need to split the string by underscore. It will return an array.
1 2 3 | let string = "adnan_tech_com" string = string.split( "_" ) // ["adnan", "tech", "com"] |
Then we can join the array by whitespace.
1 2 3 4 5 | 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.
1 2 3 | let string = "adnan_tech_com" string = string.replace( "_" , " " ) // adnan tech_com |
Checkout our more tutorials on Javascript.