30秒学会 JavaScript 片段 · 2023年11月28日

30秒学会 JavaScript 片段 – String is alphanumeric

Checks if a string contains only alphanumeric characters.

  • Use RegExp.prototype.test() to check if the input string matches against the alphanumeric regexp pattern.

代码实现

const isAlphaNumeric = str => /^[a-z0-9]+$/gi.test(str);

isAlphaNumeric('hello123'); // true
isAlphaNumeric('123'); // true
isAlphaNumeric('hello 123'); // false (space character is not alphanumeric)
isAlphaNumeric('#$hello'); // false

翻译自:https://www.30secondsofcode.org/js/s/is-alpha-numeric