How to Remove a Character from a String in JavaScript?

To remove a character from a string in JavaScript, call the replace() method on the string from which you want to remove a character by passing the character you want to remove as a first parameter and an empty string('') as a second parameter to the replace() method.

This will replace the first occurrence of the given character with an empty string('') and return the new string as a result.

For example:

// Original string
const str = "Hello World!";

// Remove character 'e' from original string
const newStr = str.replace('e', '');

// Print the new string
console.log(newStr);

Output:

"Hllo World!"

Remove All Occurrences of a Character from the String using replace() with RegEx

If you pass the character that is to be removed from the string to the replace() method as a first parameter and an empty string as a second parameter, it only removes the first occurrence of the character from the string, not all occurrences.

To solve this problem, you have to use a regular expression with the g(global) flag to replace all occurrences of the given character with an empty string.

Use the regular expression in /character/g format to remove all occurrences of the given character from the string.

The g flag in the regular expression tells the replace() method to replace all occurrences of the given character, not just the first one.

For example:

// Original string
const str = "Hello World!";

// Remove character 'o' from the entire string
const newStr = str.replace(/o/g, '');

// Print the new string
console.log(newStr);

Output:

"Hell Wrld!"

Use the split() and join() Methods to Remove a Character from the String

You can also use the split() method along with the join() method to remove a character from a given string.

The String.split() method splits a string into an array of substrings based on a specified pattern. This pattern could be a regex or a string.

On the other hand, the Array.join() method joins the array elements with a specified separator and returns a string as a result.

So, if we want to remove all occurrences of a character from a string, we have to first split the string at that character using the split() method and then join back the remaining substrings using the join() method.

For example:

// Original string
const str = "Hello World!";

// Remove character 'o' from the entire string
const newStr = str.split('o').join('');

// Print the new string
console.log(newStr);

Output:

"Hell Wrld!"

Please note that this method removes all occurrences of the given character from the string.

That’s all for the day. Happy Coding.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.