Key takeaways:
When working with strings in JavaScript, we may often need to remove certain characters to format text, filter input, or manipulate the data. In this Answer, we’ll explore various ways to remove characters from a string in JavaScript. We’ll cover several methods for eliminating specific characters, using regular expressions, and trimming characters from different string parts.
Fun fact—the longest word:
Did you know, some string operations are tested using absurdly long strings. The chemical name for titin, a protein, contains over 189,000 characters—making it one of the longest words in existence and ideal for testing string operations.
What is a string in JavaScript?
In JavaScript, strings are primitive values that contain a series of characters enclosed in a single (' '
) quote, double (" "
) quotes or backticks (` `
) that are zero-based. Strings are immutable, which means that when a string is modified, the original string doesn’t change, instead we get a new string.
Removing characters from a string
JavaScript provides built-in methods to manipulate the value of a string. With string manipulation, we can modify and transform strings using various techniques, that help us write less code and make our job easier. One of the ways we can manipulate strings is by removing characters from the string.
The following methods can be used to remove characters from a string in JavaScript:
The replace()
method
The slice()
method
The split()
method
The substr()
method
The substring()
method
Let’s look at these methods one by one:
Method 1: Using the replace()
method
The replace()
method returns a new string with its replacement. It takes in two arguments—the first argument is the character to be replaced and the second argument is the character we are replacing it with. To remove the character using the replace()
method, we replace the second argument with an empty string.
Syntax
Below is the syntax of the replce()
method: