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 digitsconsole.log(regex.test('User ID is 123')); // trueconsole.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 globalconsole.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
| Flag | Name | Description |
|---|---|---|
| g | Global search | Finds all matches instead of stopping after the first one. |
| i | Case-insensitive | Makes the entire pattern match both uppercase and lowercase letters. |
| m | Multiline | Allows start (^) and end ($) anchors to match the start/end of lines, not just the whole string. |
| s | Dot all | Allows the dot (.) to match newline characters as well. |
| u | Unicode | Enables full Unicode support, including matching surrogate pairs. |
| y | Sticky | Matches 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}$/;
^: Asserts the start of the string.[a-zA-Z0-9._-]+: Matches one or more allowed characters for the local part.@: Matches the literal '@' symbol.[a-zA-Z0-9.-]+: Matches one or more allowed characters for the domain name.\.: Matches a literal dot (escaped with a backslash).[a-zA-Z]{2,6}: Matches the top-level domain (e.g., .com, .io).$: Asserts the end of the string.
You can use the test() method to check if an email is valid:
console.log(emailRegex.test('test@example.com')); // trueconsole.log(emailRegex.test('not-an-email')); // falseconsole.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 →