JavaScript Code

How to replace specific character in a String using JavaScript?


Problem Statement

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 string is str. replace character "o" at all occurrences with "m" in str

str = "hello world";
output = str.replace(/o/g, "m");
console.log(output);