In JavaScript, a RegExp is a pattern that describes text. You write one between slashes: /cat/. That pattern matches the letters c, a, t in that order.
test() returns true or false. exec() returns the matched text and the index where it started, or null when nothing matches. A flag changes the match: i ignores letter case, and g finds every match. ^ and $ pin the pattern to the whole string.
This page teaches how a JavaScript RegExp works. The tables further down list every pattern guide in this tutorial, including test(), exec(), \d, and +.
/cat/ looks inside the string. /^cat$/ is the whole string.
/cat/.test("catch") is true. /^cat$/.test("catch") is false.
Syntax
JavaScript Syntax
A literal and the constructor build the same kind of object:
JavaScript
const literal = /cat/i;
const built = new RegExp("cat", "i");
literal.test("Cat"); // true
built.exec("The Cat sat"); // match details
const digits = /\d+/;
const same = new RegExp("\\d+");
Reference
Core Ideas
Ideas every JavaScript RegExp tutorial builds on:
Idea
Example
Remember
Literal
/cat/i
Pattern and flags between slashes
Constructor
new RegExp("cat", "i")
Use this when the pattern is a string
Yes or no
pattern.test(text)
Returns true or false
The match
pattern.exec(text)
Text and index, or null
Whole string
/^cat$/
^ is the start, $ is the end
A digit
/\d+/
One or more digits
Code
JavaScript Examples
Three short programs that show how a RegExp works in a JS tutorial.
Example 1 — Match the whole string
^ and $ mean the pattern must cover every character.
A RegExp is a pattern that describes text. You write one as /cat/ or new RegExp("cat"). test() answers true or false. exec() returns the matched text and where it started, or null when nothing matches.
/cat/i is a literal. The pattern is fixed in the source. new RegExp("cat", "i") builds the same pattern from strings, which you need when the pattern comes from a variable. Inside that string a backslash is written twice: "\\d" is the digit pattern.
Use test() for a yes-or-no check, such as form validation. Use exec() when you need the matched characters, a capture group, or the index. exec() returns null when the pattern is not found.
test() looks for the pattern anywhere in the string. cat is the start of catch, so /cat/.test("catch") is true. /^cat$/ matches only when the whole string is cat.
Practice the three examples here, then open test() and exec(). The tables below list every pattern guide in this JavaScript tutorial: flags, character classes, metacharacters, and quantifiers.