JavaScript - Remove all Occurrences of a Character in JS String
These are the following ways to remove all occurrence of a character from a given string:
1. Using Regular Expression
Using a regular expression, we create a pattern to match all occurrences of a specific character in a string and replace them with an empty string, effectively removing that character.
let str = "Geeks-for-Geeks";
let ch = "-";
let regex = new RegExp(ch, 'g');
let res = str.replace(regex, '');
console.log(res);
Output
GeeksforGeeks
2. Using the split() and join() Methods
In this approach, Using the split() method, we break a string into an array at each occurrence of a specified character. Then, with the join method, we reconstruct the array into a new string, effectively removing that character.
let str = "Geeks-for-Geeks";
let ch = "e";
let res = str.split(ch).join('');
console.log(res);
Output
Gks-for-Gks
3. Using for..in loop
The for...in loop iterates through characters of the input string. If a character doesn't match the specified one, it's appended to a new string, effectively removing the specified character.
let str = "Geeks";
let ch = "e";
let res = '';
for (let idx in str) {
if (str[idx] !== ch) {
res += str[idx];
}
}
console.log(res);
Output
Gks
4. Using String.prototype.replace() Method
Using String.prototype.replace() with a function involves passing a regular expression to match the character to be removed globally. Inside the replace function, return an empty string to remove each occurrence of the character.
let str = "Geeks";
let ch = "e";
let res = str.replace(new RegExp(ch, 'g'), () => '');
console.log(res);
Output
Gks
5. Using Array.prototype.filter() Method
The input string is converted into an array of characters using the split('') method. Then, the filter() method is used to create a new array excluding the specified character. Finally, the join('') method is used to reconstruct the array back into a string.
let str = "Geeks";
let ch = "e";
let res = str.split('').filter(c => c !== ch).join('');
console.log(res);
Output
Gks