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...