Replace specific character in a String in JavaScript
In this tutorial, you replace all occurrences of a specific character in a string using JavaScript.
Solution
To replace all occurrences of a specific character in a string, call replace() method on the string, specify the search character as regular expression with global search option as first argument, and the replacement character as second argument.
myStr.replace(/searchCharacter/g, replacementCharacter)
Program
1. Given a string value in str
. Replace character "o"
at all occurrences with "m"
in str
.
str = "hello world";
output = str.replace(/o/g, "m");
console.log(output);