JavaScript Code


How to remove all occurrences of specific character from string?


Remove all occurrences of specific character from string in JavaScript

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 value is in 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);