- 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");

 

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