OneBite.Dev - Coding blog in a bite size

check if a string contains only alphanumeric characters in Javascript

Code snippet on how to check if a string contains only alphanumeric characters in Javascript

  function isAlphanumeric(str) {
    return /^[0-9a-zA-Z]*$/.test(str);
  }

This code uses a regular expression to test if a string contains only alphanumeric characters. A regular expression is a powerful tool that can be used to match patterns within strings.

Firstly, the expression /^[0-9a-zA-Z]*$/ is used to define the pattern. This expression looks for one or more characters (indicated by the asterisk) within the range 0-9, a-z and A-Z. The caret (^) symbol indicates that the pattern should begin from the start of the string and the dollar ($) symbol indicates that the pattern should end at the end of the string.

Secondly, the .test() method is used with this expression as an argument to check if the string matches the pattern. The .test() method returns true if the string matches the defined pattern, otherwise it will return false.

Finally, the result of the .test() method is returned by the function. If true is returned, then the string only contains alphanumeric characters, otherwise it contains some other characters as well.

javascript