- Instant help with your JavaScript coding problems

Remove specific character from a string in JavaScript

Question:
How to remove a specific character from a string in JavaScript?
Answer:
const removeSpecificCharacter = (text, characterToRemove) => {
    if (!text) {
        return '';
    }
    const pattern = characterToRemove.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    
    const re = new RegExp(pattern + '$'); // From the end
    // const re = new RegExp('^' + pattern); // From the start
    // const re = new RegExp(pattern, 'g'); // From everywhere

    return text.replace(re, "");
}
Description:

Processing text such as user inputs often requires the deletion of certain unwanted characters. You can remove a specific character from a string using the replace method.

There may be several similar needs. Sometimes you only need to delete a particular character from the beginning of the text, and sometimes you only need to delete it from the end and there are times when you need to delete it from everywhere. This can be achieved using the appropriate RegExp constructor:

    const re = new RegExp(pattern + '$'); // From the end
    // const re = new RegExp('^' + pattern); // From the start
    // const re = new RegExp(pattern, 'g'); // From everywhere

It is also conceivable that the character you want to delete is itself a special regular expression. In this case, the character must first be properly prefixed, such as:

const pattern = characterToRemove.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");

 

Reference:
replace
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp.
JavaScript:
replace(substr, newSubstr)
TypeScript:
replace(searchValue: string | RegExp, replaceValue: string): string;
RegExp
The RegExp object is used for matching text with a pattern.
JavaScript:
RegExp()
TypeScript:
new (pattern: RegExp | string, flags?: string): RegExp;
Examples:
const re = new RegExp(pattern + '$');
Share "How to remove a specific character from a string in JavaScript?"
Related snippets:
Tags:
remove, delete, character, specific, string, end, start, anywhere, javascript
Technical term:
Remove specific character from a string in JavaScript