JavaScript Remove Certain Characters from String

in this post, we’ll learn Remove Character From String In JavaScript.Let’s look at all the different ways to delete a character from a string in JavaScript.
Remove character from String in JavaScript
Let’s remove character from a string in javascript. You can use one of the following methods:
- substr() — It helps to removes a character from a particular index in the String.
- replace() — The replaces a specific character/string with another character/string.
- slice() — This method help tp extracts parts of a string between the given parameters.
- replace() method with a regular expression.
JavaScript String replace()
The replace()
function replaces the specific character/string with another character/string. It returns the new String with the pattern replaced by the replacement.
The Syntax: string.replace('characterToReplace', '');
The replace() method takes two parameters, the first is the String to be replaced, and the second is the String, which is to be replaced with.
Output:
replace() method with a regular expression
This method is used to replace string using regular expression.Unlike the preceding method, this function is used to remove all occurrences of a specific character.
Output:
Removing character from string using slice()
The JavaScript String slice()
is extracted parts of a string between two arguments. The slice()
method accepts the string's starting and ending indexes and returns the string in between them.
If no ending index is supplied, the string’s length is assumed. The string ending index is to be one less than the length of the string.
Set the beginning index to 1 to remove the first character from the string. It creates a string starting with the second character and ending with the last character.
Output:
Removing a specific character using substr()
The Substring() is a built-in Javascript function that returns a portion of a string between the start and end indexes or to the end of a string.
Output:
Conclusion
The str.substr(), str.slice(), and str.replace() methods can be used to remove characters from the beginning, middle, and end of a string, respectively.
Originally published at https://www.js-tutorials.com on March 10, 2022.