Home > database >  How to use JavaScript to replace any characters found within one string from another string
How to use JavaScript to replace any characters found within one string from another string

Time:12-24

I'm pretty sure I've seen this before but for the life of me, I can't remember how it's done. I've been banging my head on this for hours!

What I would like to do is load up a series of alphanumeric and symbol characters into a string called "allowedCharacters".

Then, when a userEnteredString comes along, I'd like to do a string.replace() to remove any character NOT in "allowedCharacters" from userEnteredString.

Like this:

function parseEntry(enteredString) {
    let allowedAlphas = 'd';
    let allowedDigits = '0123456789';
    let allowedSymbols = ' ()×* -=÷\/';
    let allowedCharacters = allowedAlphas   allowedDigits   allowedSymbols;

    enteredString = enteredString.replace(allowedCharacters, '');
}

I know this is wrong and it doesn't work but I'm beating my head trying to remember how I've done this before. It's been well over a decade or two.

Basically, I'd like to set up a simple string that can contain allowed characters and then remove any single character not in that "allowed" string from another string.

CodePudding user response:

Well actually if you include all target characters in a regex character class, it should work:

function parseEntry(enteredString) {
    let allowedAlphas = 'd';
    let allowedDigits = '0123456789';
    let allowedSymbols = ' ()×* =÷\/-';
    let allowedCharacters = allowedAlphas   allowedDigits   allowedSymbols;
    let re = new RegExp("[^"   allowedCharacters   "] ");

    enteredString = enteredString.replace(re, "");
}

CodePudding user response:

You could do something like this,

modifiedString = [...enteredString].filter((c) => allowedCharacters.includes(c)).join("");
  • Related