Best way to alphanumeric check in JavaScript Best way to alphanumeric check in JavaScript javascript javascript

Best way to alphanumeric check in JavaScript


The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).

Here's a cleaned-up version of the original validation code that receives a string and returns true or false:

function isAlphaNumeric(str) {  var code, i, len;  for (i = 0, len = str.length; i < len; i++) {    code = str.charCodeAt(i);    if (!(code > 47 && code < 58) && // numeric (0-9)        !(code > 64 && code < 91) && // upper alpha (A-Z)        !(code > 96 && code < 123)) { // lower alpha (a-z)      return false;    }  }  return true;};

Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.


Check it with a regex.

Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:

if (!input_string.match(/^[0-9a-z]+$/))  show_error_or_something()

Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.

More information on Javascript regexen here:https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions