JavaScript Code

How to replace all occurrences of specific character from string?


Problem Statement

given a string and a specific character, replace all occurrences of the specified character from the string with another, using JavaScript

Solution

to replace all occurrences of specified character ch in the given string with a replacement character using JavaScript, use String replace() method

call replace() method on the string, and pass the specific character ch as regular expression with global search /ch/g, and the replacement character, as arguments

myStr.replace(/ch/g, replacement)

with this setup, replace() method returns a new string with all the occurrences of the specified character ch replaced with the replacement character in the given string

Program

1. given string is str. replace all the occurrences of the character 'a' in the string str with the character 'c'.

let str = 'apple banana cherry';
let output = str.replace(/a/g, 'c');
console.log(output);