Problem Statement
given a string and a specific character, remove all occurrences of the specified character from the string, using JavaScript
Solution
to replace all occurrences of specified character ch
from the given string 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 an empty replacement string ''
, as arguments
myStr.replace(/ch/g, '')
with this setup, replace()
method returns a new string with all the occurrences of the specified character ch
removed from the given string
Program
1. given string is str
. remove all the occurrences of the character 'a'
from the string str
let str = 'apple banana cherry';
let output = str.replace(/a/g, '');
console.log(output);