String Is Alphanumeric

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to check if a given string contains only alphanumeric characters using JavaScript. We will use a regular expression pattern to match the input string against alphanumeric characters and return a boolean value indicating whether the string is alphanumeric or not. This lab will help you understand how to work with regular expressions in JavaScript and how to use them to solve practical problems.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28407{{"`String Is Alphanumeric`"}} javascript/data_types -.-> lab-28407{{"`String Is Alphanumeric`"}} javascript/arith_ops -.-> lab-28407{{"`String Is Alphanumeric`"}} javascript/comp_ops -.-> lab-28407{{"`String Is Alphanumeric`"}} end

Checking if a String is Alphanumeric

If you want to practice coding, open the Terminal/SSH and type node. Here's a function that checks if a string contains only alphanumeric characters:

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

To use it, call isAlphaNumeric with a string as its argument. It will return true if the string contains only alphanumeric characters, and false otherwise.

For example:

isAlphaNumeric("hello123"); // true
isAlphaNumeric("123"); // true
isAlphaNumeric("hello 123"); // false (contains a space character)
isAlphaNumeric("#$hello"); // false (contains non-alphanumeric characters)

The RegExp.prototype.test() method is used to check if the input string matches against the alphanumeric pattern, which is represented by the regular expression /^[a-z0-9]+$/gi. This pattern matches any sequence of one or more lowercase letters or digits, and the g and i flags make the matching case-insensitive.

Summary

Congratulations! You have completed the String Is Alphanumeric lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like