DEV Community

SCDan0624
SCDan0624

Posted on

Javascript Regex Part 2 Character Classes

Intro

In my part one of my previous post I displayed how to find literal pattern matches. If you need to search for a literal pattern with some flexibility you can use regex character classes.

Character Classes

Character classes allow you to define a set of characters you wish to match by using square brackets:

let myPet = "cat"
let notMyPet = "cut"
let myRegex = /c[au]t/

myPet.match(myRegex) // Returns ["cat"]
notMyPet.match(myRegex) // Returns ["cut"]
Enter fullscreen mode Exit fullscreen mode

Match a Range

If you need to match a large set of letters you can also define a range using a hyphen:

let myPet = "cat"
let notMyPet = "bat"
let forMyFloor = "mat"
let myRegex = /[b-m]at/

myPet.match(myRegex) // Returns ["cat"]
notMyPet.match(myRegex) // Returns ["bat"]
forMyFloor.match(myRegex) // Returns ["mat"]
Enter fullscreen mode Exit fullscreen mode

You can also a hyphen to match any number in a string:

let myName = "Dan061983"
let myRegex = /[a-z0-9]/ig // Will match all letters and numbers in myName
myName.match(myRegex)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)