Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use javascript to remove characters from a string based on a whitelist

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

like image 209
Aaron Avatar asked Jun 11 '13 22:06

Aaron


3 Answers

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

like image 173
nnnnnn Avatar answered Sep 20 '22 14:09

nnnnnn


What you're looking for is regular expressions:

"The result is -2,003% of the total".match(/[\d,%\-]+/)[0]; //=> -2,003%
like image 43
elclanrs Avatar answered Sep 24 '22 14:09

elclanrs


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.

like image 30
Explosion Pills Avatar answered Sep 20 '22 14:09

Explosion Pills