How to replace all occurrences of a character in a string in JavaScript?
The replace() method in JavaScript searches a string for a specified value or regular expression and returns a new string in which the specified values are replaced. However, if a string contains repeated words, the replace() method only changes the first occurrence of a string.
How to replace all occurrences of a character in a string in JavaScript?
str = "A B A C";
repStr = str.replace('A', 'X');
alert(repStr);
Output:
X B A C
When you run the above script, it will returns “X B A C”. Here you can see, the first occurrence “A” is replaced with “X” and the second is always the same. So how can you change all occurrences of a string in JavaScript?
Replace all occurrences using Split() and join()
You can replace all occurrences of a string using the Split() and join() functions.
str = "A B A C";
repStr = str.split("A").join("X");
alert(repStr);
Output:
X B X C
Replace all occurrences using regular expression
You can replace all occurrences of a string using regular expressions.
str = "A B A C";
newStr = replaceAll(str,'A','X');
alert(newStr);
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
Output:
X B X C




