简体   繁体   中英

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

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.

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

You could do something like this,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM