Replace all occurrences of specific character from string in JavaScript
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 value is in 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);