Premium lesson

Matching Patterns With Regular Expressions in JavaScript

JavaScript·3 min read·Jan 1, 2025

In JavaScript, regular expressions, often abbreviated regex or regexp, are patterns used to match, validate, extract, and replace character combinations in strings.

Creating a regular expression

To create a new regular expression object, you can write a regex literal using the double slash syntax //:

const regex = /pattern/;

Where pattern is a string or regular expression.

Matching patterns in strings

Checking if a pattern exists

To check whether a pattern exists in a string, you can use the test() method of the regex object:

let exists = /pattern/.test(string);

Where:

  • /pattern/ is a regular expression.
  • string is a string of characters.

This function returns true if the pattern exists, and false otherwise.

Listing all matching patterns

To list all the matched occurrences of the pattern in a string, you can use the match() method of the string:

icon light bulb key

Unlock the Build CLI Apps in JavaScript & Node.js module

Learn how to build, integrate, and safeguard scalable CLI tools, scripts, and apps with JavaScript, Node.js, npm, and Git.

You get immediate access to:

  • 45 focused lessons across JavaScript, Node.js, npm, and Git
  • 17 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module