Sling Academy
Home/JavaScript/JavaScript: Check if a string contains non-alphanumeric characters

JavaScript: Check if a string contains non-alphanumeric characters

Last updated: June 17, 2023

Non-alphanumeric characters refer to any character that is not a letter (A-Z, a-z) or a digit (0-9). Examples include symbols (!, @, #), punctuation marks (., ?, :), and whitespace characters (space, tab).

When developing web applications with JavaScript, there might be cases where you want to check whether a string contains non-alphanumeric characters or not (such as when you want to validate a username provided by a user during registration). This concise, example-based article will walk you through a couple of different approaches to doing so. Let’s get started!

Using regular expressions

This solution uses a regular expression with the test() method to check if a string contains non-alphanumeric characters. The regular expression pattern is shown below:

/[^a-zA-Z0-9]/

Code example:

// define a reusable function
const hasNonAlphanumeric = (str) => {
  const regex = /[^a-zA-Z0-9]/;
  return regex.test(str);
};

// Example usage

console.log(hasNonAlphanumeric('wolf123')); 
// false

console.log(hasNonAlphanumeric('slingacademy.com')); 
// true (dot is non-alphanumeric)

console.log(hasNonAlphanumeric('sling_academy')); 
// true (underscore is non-alphanumeric)

This approach is concise, efficient, and reliable. You can also modify the regular expression pattern a little bit in some specific use cases.

Using ASCII Range Comparison

The main idea of this approach is to use the charCodeAt() method of the string object to get the numeric value of each character in the input string and compare it with a range of values that correspond to alphanumeric characters.

The steps:

  1. Loop through each character in the input string using a for loop or a forEach method.
  2. Use the charCodeAt() method of the string object to get the numeric ASCII value of each character. For example, 'A'.charCodeAt(0) returns 65.
  3. Check if the ASCII value falls outside the alphanumeric range (between 48-57, 65-90, 97-122).
  4. Return true if a non-alphanumeric character is found, false otherwise.

Code example:

// define a reusable function
const hasNonAlphanumeric = (str) => {
  for (let i = 0; i < str.length; i++) {
    const charCode = str[i].charCodeAt();
    if (
      (charCode < 48 || charCode > 57) && // not 0-9
      (charCode < 65 || charCode > 90) && // not A-Z
      (charCode < 97 || charCode > 122) // not a-z
    ) {
      return true;
    }
  }
  return false;
};

// Example usage

console.log(hasNonAlphanumeric('abc123DEF2024'));
// false

console.log(hasNonAlphanumeric('slingacademy.com'));
// true (dot is non-alphanumeric)

console.log(hasNonAlphanumeric('sling_academy'));
// true (underscore is non-alphanumeric)

This approach might be faster than using regular expressions, especially for long strings or complex patterns. It does not rely on regex, which may have different implementations across browsers or platforms. However, the trade-off is that the code is longer and less readable.

Next Article: JavaScript: Convert String to Hex and Vice Versa

Previous Article: JavaScript: 2 Ways to Format a String with Leading Zeros

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration