It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 63 - Regular Expressions: Character Classes and Special Characters

In this lesson, we'll explore character classes and special characters in regular expressions, which allow you to match specific types of characters efficiently.


Understanding Character Classes

Character classes help match specific types of characters instead of exact text.

Character Class Description Example Pattern Matches
\d Any digit (0-9) /\d/ "abc123" ? 1
\w Any word character (a-z, A-Z, 0-9, _) /\w/ "Hello_42" ? H
\s Any whitespace (space, tab, newline) /\s/ "Hello World" ? " "
. Any single character (except newline) /./ "cat" ? c

Example:

const text = "My number is 42!";
const pattern = /\d/;
console.log(text.match(pattern)); // Output: ["4"]

Using Ranges in Character Classes

  • [a-z] ? Any lowercase letter
  • [A-Z] ? Any uppercase letter
  • [0-9] ? Any digit
  • [aeiou] ? Any vowel
  • [^a-z] ? NOT a lowercase letter

    Example:

    const pattern = /[0-9]+/;
    console.log("Order 325".match(pattern)); // Output: ["325"]

Try Your Hand

  1. Write a regex to find all vowel letters in "Javascript is fun!".
  2. Create a regex to match any three-letter word in "The cat sat on the mat.".