JavaScript RegExp

Beginner
8 min read
Updated: Nov 2026
3 examples
53 pattern guides

Definition and Usage

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(), flags, lastIndex, \d, and +.

/cat/ looks inside the string. /^cat$/ is the whole string.

/cat/.test("catch") is true. /^cat$/.test("catch") is false.

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+");

Core Ideas

Ideas every JavaScript RegExp tutorial builds on:

IdeaExampleRemember
Literal/cat/iPattern and flags between slashes
Constructornew RegExp("cat", "i")Use this when the pattern is a string
Yes or nopattern.test(text)Returns true or false
The matchpattern.exec(text)Text and index, or null
Whole string/^cat$/^ is the start, $ is the end
A digit/\d+/One or more digits
Flags string/cat/gi.flagsRead-only summary of all flags
Next search indexregex.lastIndexUsed with the g or y flag

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.

JavaScript
const whole = /^cat$/;

console.log(whole.test("cat"));
console.log(whole.test("catch"));
console.log(/cat/.test("catch"));
test() tutorial

How It Works

  1. /^cat$/ matches "cat" and nothing else, so the first call is true.
  2. "catch" has extra letters, so the anchored pattern is false.
  3. /cat/ finds those three letters inside "catch", so it is true.

Example 2 — Read the match and its index

The i flag matches Cat and cat. exec() returns the text it found.

JavaScript
const found = /cat/i.exec("The Cat sat");

console.log(found[0]);
console.log(found.index);
exec() tutorial

How It Works

  1. /cat/i matches Cat because i ignores letter case.
  2. found[0] is the matched text, "Cat".
  3. index is 4. The match starts after "The ".

Example 3 — Digits, and replace every match

\d+ is one or more digits. The g flag lets replace change every hit.

JavaScript
console.log(/\d+/.test("room 12"));
console.log("ab12cd".match(/\d+/)[0]);
console.log("hello".replace(/l/g, "L"));
\d tutorial

How It Works

  1. \d+ finds 12 inside "room 12", so test is true.
  2. match returns that digit run. Index 0 is "12".
  3. /l/g replaces both l characters, so "hello" becomes "heLLo".

Pattern Guides in This Tutorial

Every RegExp guide in this JavaScript series (53 tutorials). Open one when you need that token.

Methods

4

Ask a pattern a yes-or-no question, or read the text it found.

PatternDescriptionTutorial
test()Return true or false when a pattern matches anywhere in a string.Open
exec()Run a match and return capture groups, index, and input — or null.Open
toString()Return the /pattern/flags string representation of a RegExp.Open
compile()Legacy method to recompile an existing RegExp (prefer new RegExp).Open

Properties

12

Read flags and state on the RegExp object. These are values, not function calls.

PatternDescriptionTutorial
constructorPoints to the RegExp function that created the regex object.Open
globalTrue when the g flag is set — find all matches, not just the first.Open
ignoreCaseTrue when the i flag is set — case-insensitive matching.Open
multilineTrue when the m flag is set — ^ and $ match each line.Open
dotAllTrue when the s flag is set — the . wildcard also matches newlines.Open
stickyTrue when the y flag is set — match only at lastIndex.Open
unicodeTrue when the u flag is set — Unicode code point mode.Open
unicodeSetsTrue when the v flag is set — Unicode sets mode.Open
hasIndicesTrue when the d flag is set — exec results include start/end indexes.Open
flagsRead-only string of every flag on the RegExp (for example "gi").Open
sourceRead-only pattern text without flags — useful for cloning a RegExp.Open
lastIndexWritable index where the next g or y search starts.Open

Character classes

5

Match one character from a set, a range, or either of two patterns.

PatternDescriptionTutorial
[0-9]Character class matching any digit from 0 through 9.Open
[abc]Match any one character from the set inside the brackets.Open
[^0-9]Negated class — match any character that is not a digit.Open
[^abc]Negated class — match any character not in the set.Open
(x|y)Alternation — match either the left or right sub-pattern.Open

Metacharacters

18

Short tokens for a digit, whitespace, a word character, or an escape.

PatternDescriptionTutorial
\bWord boundary between a word and non-word character.Open
\rCarriage return character.Open
\dShorthand for any digit — equivalent to [0-9].Open
.Wildcard — matches any character except newline (by default).Open
\fForm feed character.Open
\nLine feed (newline) character.Open
\DAny non-digit character.Open
\SAny non-whitespace character.Open
\WAny non-word character (not letter, digit, or _).Open
\BNot a word boundary — opposite of \b.Open
\0Null character (U+0000).Open
\sWhitespace — spaces, tabs, newlines, and similar.Open
\tHorizontal tab character.Open
\uXXXXUnicode code point by four hex digits.Open
\vVertical tab character.Open
\wWord character — letters, digits, and underscore.Open
\xHHByte value by two hex digits.Open
\oooByte value by one to three octal digits (legacy).Open

Flags

4

Change the match: every hit, any letter case, or each line.

PatternDescriptionTutorial
d (indices)HasIndices flag — exec results include match indices.Open
g (global)Global flag — continue searching after each match.Open
i (ignoreCase)Ignore case when matching letters.Open
m (multiline)Multiline flag — ^ and $ match line boundaries.Open

Anchors and lookahead

4

Pin a match to the start or end, or peek ahead without taking those characters.

PatternDescriptionTutorial
^Start anchor — match must begin at the start (or line with m).Open
$End anchor — match must end at the end (or line with m).Open
(?!…)Negative lookahead — succeed only if pattern ahead fails.Open
(?=…)Positive lookahead — require a pattern ahead without consuming it.Open

Quantifiers

6

Say how many times the previous token may repeat.

PatternDescriptionTutorial
+One or more repetitions of the preceding token.Open
?Zero or one repetition — makes the preceding token optional.Open
*Zero or more repetitions of the preceding token.Open
{X}Exactly X repetitions of the preceding token.Open
{X,}At least X repetitions (no upper limit).Open
{X,Y}Between X and Y repetitions inclusive.Open

Frequently Asked Questions

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.
Boolean properties such as global, ignoreCase, and multiline report which flags were set. flags is the full flag string. source is the pattern text. lastIndex is where the next g or y search starts. Open the Properties table below for each guide.
Practice the three examples here, then open test() and exec(). The tables below list every pattern guide in this JavaScript tutorial: methods, properties, flags, character classes, metacharacters, and quantifiers.

Start with test()

Open the yes-or-no guide—syntax, examples, and FAQs.

test() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful