I can't seem to find the answer to this. I would like a generic function that allows me to remove all characters from a string that do not exist in a whitelist of characters.
var validChars = "0123456789%-"
var stringToTest = "The result is -2,003% of the total"
I'd like a function that would produce the result: -2,003%
Thanks for any help. AD
"I would like a generic function"
OK, like this:
function removeChars(validChars, inputString) {
var regex = new RegExp('[^' + validChars + ']', 'g');
return inputString.replace(regex, '');
}
var newString = removeChars('01234567890%-', "The result is -2,003% of the total");
The new RegExp()
part creates (for your particular input) a regex like this:
/[^01234567890%-]/g
Note that for this to work the way you intend a hyphen in the list of valid characters would need to be last in the list - you could add some extra code to test for this and move it. Also if the white list contained other characters that have special meaning to regular expressions (e.g., ]
) you'd have to escape them. I leave such details as an exercise for the reader...
What you're looking for is regular expressions:
"The result is -2,003% of the total".match(/[\d,%\-]+/)[0]; //=> -2,003%
var regexp = new RegExp("[^" + validChars + "]", "g");
console.log(stringToTest.replace(regexp, ""));
Beware of validChars
containing user input; in that case it should be properly escaped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With