Check if string is alphanumeric or alphanumeric + some allowed chars
The fastest alphanumeric method is likely as mentioned at: Best way to alphanumeric check in Javascript as it operates on number ranges directly.
Then, to allow a few other extra chars sanely we can just put them in a Set
for fast lookup.
I believe that this implementation will deal with surrogate pairs correctly correctly.
#!/usr/bin/env node
const assert = require('assert');
const char_is_alphanumeric = function(c) {
let code = c.codePointAt(0);
return (
// 0-9
(code > 47 && code < 58) ||
// A-Z
(code > 64 && code < 91) ||
// a-z
(code > 96 && code < 123)
)
}
const is_alphanumeric = function (str) {
for (let c of str) {
if (!char_is_alphanumeric(c)) {
return false;
}
}
return true;
};
// Arbitrarily defined as alphanumeric or '-' or '_'.
const is_almost_alphanumeric = function (str) {
for (let c of str) {
if (
!char_is_alphanumeric(c) &&
!is_almost_alphanumeric.almost_chars.has(c)
) {
return false;
}
}
return true;
};
is_almost_alphanumeric.almost_chars = new Set(['-', '_']);
assert( is_alphanumeric('aB0'));
assert(!is_alphanumeric('aB0_-'));
assert(!is_alphanumeric('aB0_-*'));
assert(!is_alphanumeric('??'));
assert( is_almost_alphanumeric('aB0'));
assert( is_almost_alphanumeric('aB0_-'));
assert(!is_almost_alphanumeric('aB0_-*'));
assert(!is_almost_alphanumeric('??'));
Tested in Node.js v10.15.1.