Use the replace() method to remove specific characters from string JavaScript. This method searches a string for a value or a regular expression and returns a new string with the value(s) replaced.
string.replace(searchValue, newValue)
The repace() method takes two parameters, the first is the String to be replaced, and the second is the String, which is to be replaced. In this case, the first argument is the character to be removed, and the second parameter can be given as the empty string.
Remove specific characters from string JavaScript
Simple example code removes the first occurrence of the String.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
str = 'Hello cy Adele';
newStr = str.replace('c', '');
console.log('Original String: ', str);
console.log('After character removed: ', newStr);
</script>
</body>
</html>
Output:
Use replaceAll() to replace all occurrences of given char
<script>
var oldString = "Hello World!";
var newString = oldString.replaceAll("o", "");
console.log(newString); // Hell Wrld!
</script>
Using a replace() method with a regular expression to select every occurrence in a string, and remove it.
<script>
str = 'AppDividend';
newStr = str.replace(/d/g, '');
console.log(newStr);// AppDivien
</script>
You can split the string by the character you want to remove and then join it back together.
let str = "Hello World!";
let charToRemove = "o";
let newStr = str.split(charToRemove).join('');
console.log(newStr); // "Hell Wrld!"
Using a Loop
You can iterate through the string and build a new string without the unwanted character.
let str = "Hello World!";
let charToRemove = "o";
let newStr = '';
for (let char of str) {
if (char !== charToRemove) {
newStr += char;
}
}
console.log(newStr); // "Hell Wrld!"
Do comment if you have any doubts or suggestions on this Js remove char code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version