In JavaScript, characters can be removed from a string using different built-in methods. Since strings are immutable, each approach creates and returns a new string.
- Remove the first or all occurrences of a character.
- Remove a character based on its position or index.
- Choose an approach based on whether you need simple replacement or custom string manipulation.
These are the following approaches to remove a character from a string in JavaScript.
Approach 1: Using the replace() Method
The replace() method removes the first occurrence of a specified character by replacing it with an empty string.
let str = "GeeksForGeeks";
let result = str.replace("G", "");
console.log(result);
Output
eeksForGeeks
Approach 2: Using replace() with a Regular Expression
A regular expression with the global (g) flag removes all occurrences of a specified character.
let str = "GeeksForGeeks";
let result = str.replace(/G/g, "");
console.log(result);
Output
eeksForeeks
Approach 3: Using the substring() Method
The substring() method removes a character at a specific index by combining the parts before and after that character.
let str = "Hello World";
let result = str.substring(0, 4) + str.substring(5);
console.log(result);
Output
Hell World
Approach 4: Using the slice() Method
The slice() method can also remove a character at a specific position by joining the portions before and after it.
let str = "Hello World";
let result = str.slice(0, 4) + str.slice(5);
console.log(result);
Output
Hell World
Approach 5: Using split() and join()
The split() method divides the string around the specified character, and join() combines the remaining parts without that character.
let str = "GeeksForGeeks";
let result = str.split("G").join("");
console.log(result);
Output
eeksForeeks
Approach 6: Using Array.filter()
This approach converts the string into an array of characters, filters out the unwanted character, and joins the remaining characters.
let s = "GeeksForGeeks";
let c = 'G';
let res = Array.from(s)
.filter(char => char !== c)
.join('');
console.log(res);
Output
eeksForeeks