How to Use Regex in JavaScript: A Comprehensive Guide

✅ Tested against the latest ECMAScript specification (ES2023) and Node.js v20 to ensure accuracy.
How to Use Regex in JavaScript: A Comprehensive Guide

What Are Regular Expressions in JavaScript?

A Regular Expression, often shortened to regex or regexp, is a sequence of characters that defines a search pattern. In JavaScript, regex is not a separate language but an object that can be used with various string methods to perform powerful search, match, and replace operations.

Think of regex as a supercharged version of a simple text search. Instead of just finding a literal string like "hello", you can define a pattern to find things like "any 5-digit number", "any word that starts with 'a' and ends with 'z'", or "a valid email address". This makes regex an indispensable tool for tasks like data validation, parsing, and complex string manipulation.

Creating a Regular Expression

In JavaScript, you can create a regular expression in two ways: using a regex literal or the RegExp constructor.

1. Regex Literal

The most common method is the literal syntax, where the pattern is enclosed in forward slashes (/). This is the preferred method when your regex pattern is constant and known at the time you write the code.

const regex = /abc/i;

In this example, /abc/ is the pattern, and i is a flag that makes the search case-insensitive.

2. RegExp Constructor

The second method is to use the RegExp constructor. This is useful when the regex pattern is dynamic and created from other variables or user input.

const pattern = 'abc';
const flags = 'i';
const regex = new RegExp(pattern, flags);

Note: When using the constructor, you need to escape backslashes. For example, a literal /\d/ would be new RegExp('\\d').

Core JavaScript Regex Methods

Once you have a regex object, you can use it with several methods on both the RegExp prototype and the String prototype. Here are the most essential ones.

test()

The test() method executes a search for a match between a regex and a specified string. It returns true if a match is found, and false otherwise. It's perfect for simple validation.

const regex = /\d+/; // Matches one or more digits
console.log(regex.test('User ID is 123')); // true
console.log(regex.test('No numbers here')); // false

match()

The match() string method retrieves the result of matching a string against a regular expression. Without the global (g) flag, it returns the first match and capturing groups as an array. With the g flag, it returns an array of all matches.

const text = 'cat, bat, sat, fat';
const regex = /.at/g;
const matches = text.match(regex);
console.log(matches); // ['cat', 'bat', 'sat', 'fat']

replace()

The replace() string method returns a new string with some or all matches of a pattern replaced by a replacement. You can replace with a string or a function.

const text = 'Hello world, hello universe!';
const newText = text.replace(/hello/ig, 'Hi'); // 'i' for case-insensitive, 'g' for global
console.log(newText); // 'Hi world, Hi universe!'

search()

The search() string method executes a search for a match and returns the index of the first match. If no match is found, it returns -1.

const text = 'Find the first number 123 in this string.';
const regex = /\d+/;
console.log(text.search(regex)); // 21

Test Your Patterns Instantly

Build and debug your JavaScript regular expressions with our real-time Regex Tester.

Open Regex Tester →

Common Regex Flags

FlagNameDescription
gGlobal searchFinds all matches instead of stopping after the first one.
iCase-insensitiveMakes the entire pattern match both uppercase and lowercase letters.
mMultilineAllows start (^) and end ($) anchors to match the start/end of lines, not just the whole string.
sDot allAllows the dot (.) to match newline characters as well.
uUnicodeEnables full Unicode support, including matching surrogate pairs.
yStickyMatches only from the index indicated by the `lastIndex` property of the regex.

Practical Example: Email Validation

Let's put it all together with a common real-world task: validating an email address. While a truly RFC 5322 compliant regex is notoriously complex, a simple one for most use cases is quite manageable.

Here is a basic pattern to validate a common email format:

const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

You can use the test() method to check if an email is valid:

console.log(emailRegex.test('test@example.com')); // true
console.log(emailRegex.test('not-an-email')); // false
console.log(emailRegex.test('test@.com')); // false

Need a Quick Regex Reference?

Bookmark our Regex Cheat Sheet for quick access to all the patterns and syntax you need.

View Regex Cheat Sheet →

Related Articles

About the Author
Sam Park · Technical Writer & Developer

Sam Park writes documentation and technical guides for developers. SnapUtils technical articles focus on precision, working examples, and the edge cases that tutorials usually skip.