Remove all occurrences of a character in a string using JavaScript
Last Updated :
15 Sep, 2023
Removing all occurrences of a character in a string means eliminating every instance of a particular character from the given string, resulting in a modified string without that character.
Approaches to Remove all occurrences of a character in a string using JavaScript
- Using a JavaScript Regular Expression
- Using the split() and join() methods
- Using for..in loop
In this approach, 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.
Syntax:
let regex = new RegExp(charToRemove, 'g');
Example: This example shows the use of the above-explained approach.
Javascript
let inputStr = "Geeks-for-Geeks" ;
let charToRemove = "-" ;
let regex = new RegExp(charToRemove, 'g' );
let result = inputStr.replace(regex, '' );
console.log(result);
|
Approach 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.
Syntax:
let result = inputStr.split(removeStr).join('');
Example: This example shows the use of the above-explained approach.
Javascript
let inputStr = "Hello, Geeks!" ;
let removeStr = "e" ;
let result = inputStr.split(removeStr).join( '' );
console.log(result);
|
Approach 3: Using for..in loop
In this approach, 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.
Syntax:
for (let i in obj1) {
// Prints all the keys in
// obj1 on the console
console.log(i);
};
Example: This example shows the use of the above-explained approach.
Javascript
function removeCharacter(str1, str2) {
let result = '' ;
for (let index in str1) {
if (str1[index] !== str2) {
result += str1[index];
}
}
return result;
}
let inputStr = "Geeks" ;
let str2 = "e" ;
let result = removeCharacter(inputStr, str2);
console.log(result);
|
Share your thoughts in the comments
Please Login to comment...