zondag 31 januari 2010

How to check a string value to contain a set of predefined characters with a regular expression in javascript

This struck me only now: if you want to check some string to contain a set of predefined characters using a regular expression for that set, in javascript you just need to compare the length of the matching result to the length of the input string. Like this:

var str = 'this string can contain nothing else but digits, spaces,'+
          'commas and alphabetic characters';
alert(String(str.match(/[a-z\,\.\s0-9]/ig).length === str.length));
//returns true

The set [a-z\,\.\s0-9] contains spaces, letters (case insensitive), digits, dots and comma's. Matching the set to a string that only contains characters from the set should deliver a resulting array with exactly the length of the input string. And yes, it does.

Why didn't I think of that before? Well ehr....