Match Patterns With Regular Expressions in JavaScript

JavaScript·2 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:

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.