Wednesday, September 29, 2010

Javascript - strip off illegal characters from string

Recently had to come up with a piece of javascript to strip off a set of illegal characters from strings before passing down to the persistance layer.

Took me a while to come up with a regex for the replace, not because it's particularly difficult, but because I suck at regexes (and I am no js expert either).

I thought it could be handy to have this functionality as a string prototype:
// strips off illegal chars &%$
String.prototype.stripOffIllegalChars = function() {
 return this.replace(/[&%$]/g, "");
}
The /g above means that the replace will be global (so not just the first of those characters will be replaced).

It can be used like this on any string:
var dirtyString = "blah$blah%blah&";
var cleanString = dirtyString.stripOffIllegalChars();
Hopefully it'll save some time to the next in line.