Skip to main content

How to Remove a Character from a String in JavaScript

how-to-remove-character-from-string-in-javascript

How to Remove a Character from a String in JavaScript

When working with strings in JavaScript, you might encounter situations where you need to remove a specific character from a string. Removing a character can be useful for various purposes, such as sanitizing user input, manipulating data, or formatting strings. Fortunately, JavaScript provides multiple methods to accomplish this task. You can effectively remove the targeted character from a string. These methods offer flexibility and cater to different use cases, allowing you to customize the removal process based on your specific needs.

In this article, we will explore these different approaches to removing a character from a string in JavaScript, empowering you to handle string manipulation tasks more efficiently and enhancing the functionality of our code.


01. Using "String.replace()" with Regular Expression

var string = "Hello, World!";
var characterToRemove = ",";
var modifiedString = string.replace(new RegExp(characterToRemove, "g"), "");
console.log(modifiedString);

Output

"Hello World!"

In this method, String.replace() is utilized with a regular expression containing the character to remove. By specifying the global flag ("g"), all occurrences of the character are replaced with an empty string.



02. Using "String.split()" And "Array.join()"

var string = "Hello, World!";
var characterToRemove = ",";
var stringArray = string.split(characterToRemove);
var modifiedString = stringArray.join("");
console.log(modifiedString);

Output

"Hello World!"

Here, String.split() is used to split the string into an array based on the character to remove. Then, Array.join() concatenates the array elements back into a string without the specified character.



03. Using "String.replaceAll()" (from ECMAScript 2021)

var string = "Hello, World!"; 
var characterToRemove = ","; 
var modifiedString = string.replaceAll(characterToRemove, ""); 
console.log(modifiedString);

Output

"Hello World!"

In this method, String.replaceAll() is directly used to replace all occurrences of the character with an empty string. Note that this method is available starting from ECMAScript 2021 and may not be supported in older browsers or environments.


04. Using a combination of "String.split()" and "Array.filter()"

var string = "Hello, World!";
var characterToRemove = ",";
var modifiedString = string
  .split("").filter(function(char) {
    return char !== characterToRemove;
  }).join("");
console.log(modifiedString);

Output

"Hello World!"

Here, the string is first split into an array of individual characters using String.split(""). Then, Array.filter() is applied to exclude the character to remove from the array. Finally, Array.join() concatenates the remaining characters back into a string.


Comments