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