Skip to content
Tutorials Center
My learning

Topics

Lesson 114 of 156 ยท Built-in Tools

Regular Expressions

Learn regular expression syntax in JavaScript - literal characters, character classes, quantifiers, anchors, groups, alternation and the flags that change matching.

String methods like includes() and indexOf() find exact text. But often you want to find text that fits a shape: "any five digits", "a word that starts with a capital letter", "a date like 2026-10-14". A regular expression (regex for short) is a tiny language for describing such shapes.

Regular expressions look cryptic at first โ€” /^\d{3}-\d{4}$/ is not exactly friendly โ€” but they are built from a small number of pieces. In this lesson you will learn those pieces one at a time: literal characters, character classes, quantifiers, anchors, groups and flags. The next lesson puts them to work with the string methods that search, extract and replace.

Creating a regular expression

A regex is an object of type RegExp. You usually write it as a literal between slashes:

JavaScript
const pattern = /cat/;

When the pattern comes from a variable โ€” for example, a search box โ€” use the constructor, which takes a string:

JavaScript
const word = "cat";
const pattern = new RegExp(word, "i"); // same as /cat/i

To try a pattern, the simplest method is test(), which returns true or false:

JS Your first patterns

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Most characters in a pattern simply match themselves. Letters, digits and spaces are literal. The interesting part is the characters that mean something special.

Special characters and escaping

These characters have special meaning in a regex:

TEXT
.  ^  $  *  +  ?  (  )  [  ]  {  }  |  \  /

To match one of them literally, put a backslash in front: \. matches a real dot, \$ a real dollar sign, \( an opening parenthesis.

JavaScript
/3.14/.test("3x14");   // true  โ€” "." means "any character"
/3\.14/.test("3x14");  // false โ€” "\." means a real dot
/\$\d+/.test("Total: $42"); // true

With new RegExp(), remember that the backslash must also be escaped in the string: new RegExp("\\d+") is the same as /\d+/. This double-escaping is a common source of bugs, which is one reason to prefer literals.

Character classes

A character class matches one character from a set.

Pattern Matches oneโ€ฆ
[aeiou] vowel
[a-z] lowercase letter a to z
[A-Za-z0-9] ASCII letter or digit
[^0-9] character that is not a digit (^ first means "not")
. any character except a line break
\d digit, same as [0-9]
\w "word" character: [A-Za-z0-9_]
\s whitespace: space, tab, line break and other spaces
\D, \W, \S the opposite of \d, \w, \s

Inside square brackets most special characters lose their meaning: [.?] matches a real dot or question mark. A hyphen is literal when it comes first or last: [-+].

JS Character classes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

\w and \d only know ASCII. \w does not match "รฉ", "รŸ" or "ะถ". For letters in any language, use the u flag with a Unicode property: /\p{L}/u matches any letter, /\p{Lu}/u any uppercase letter, /\p{N}/u any number. Unicode property escapes work in all modern browsers.

Quantifiers: how many?

A quantifier after a character, class or group says how many times it may repeat:

Quantifier Meaning
* 0 or more
+ 1 or more
? 0 or 1 (optional)
exactly 3
{2,4} 2 to 4
{2,} 2 or more
JavaScript
/colou?r/      // "color" or "colour"
/\d+/          // one or more digits: "7", "2026"
/\d{4}-\d{2}/  // "2026-10"
/ha(ha)*/      // "ha", "haha", "hahaha"...

Greedy and lazy

Quantifiers are greedy: they grab as much text as they can while still letting the whole pattern match. Adding ? after a quantifier makes it lazy โ€” it takes as little as possible.

JS Greedy vs lazy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Anchors and boundaries

Anchors match a position, not a character:

  • ^ โ€” the start of the string
  • $ โ€” the end of the string
  • \b โ€” a word boundary (between a \w character and a non-\w character)

Anchors are essential for validation. Without them, a pattern is happy to match part of the text:

JavaScript
/\d{5}/.test("ZIP 902101 extra");   // true โ€” five digits appear somewhere
/^\d{5}$/.test("902101");           // false โ€” must be exactly five digits
/^\d{5}$/.test("90210");            // true

/\bcat\b/.test("concatenate");      // false โ€” "cat" is not a whole word here
/\bcat\b/.test("the cat sat");      // true

Escape sequences and the opposite boundary

Besides the shorthand classes, a pattern can name characters you can't type on a keyboard or see on screen. They all start with a backslash:

Pattern Matches
\n line feed (the Unix line break)
\r carriage return (half of a Windows line break, \r\n)
\t tab
\v vertical tab (rare)
\f form feed (rare)
\0 the NUL character (code 0); it must not be followed by a digit
\xHH the character with two hex digits, such as \x41 for "A"
\uHHHH the UTF-16 code unit with four hex digits, such as รฉ for "รฉ"
\u{1F600} any code point, with the u flag

Two more details. \B is the opposite of \b: it matches a position that is not a word boundary, so /\Bcat/ finds "cat" only inside a word (as in "concatenate"). Like \b, it is zero-width and consumes nothing. And the dot does not match line terminators (\n, \r, โ€จ, โ€ฉ) unless you add the s flag. Text may come from Windows or Unix sources, so split lines with /\r?\n/ rather than just "\n".

JS Escape sequences, negated sets and alternation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Alternation has the lowest priority. /^cat|dog$/ means "starts with cat" or "ends with dog". Wrap the choices in a group, /^(cat|dog)$/, to anchor both.

Groups and alternation

Parentheses do two jobs. They group pieces so a quantifier applies to all of them, and they capture the text that the group matched, so you can read it afterward.

The pipe | means "or". It has the lowest priority of all, so use a group to limit its reach: /^(cat|dog)s?$/.

JS Capturing groups

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Inside a pattern, a backreference refers to what an earlier group captured: \1 for the first group, \k<name> for a named one. For example, /\b(\w+) \1\b/ finds a doubled word, as in "the the".

Flags

Flags go after the closing slash (/pattern/gi) or as the second argument of new RegExp(). They change how the whole pattern behaves.

Flag Name Effect
g global find all matches, not just the first
i ignore case a matches A
m multiline ^ and $ match at the start and end of every line
s dotAll . also matches line breaks
u unicode full Unicode support: \p{โ€ฆ}, emoji as single characters
v unicodeSets an upgraded u with set operations in classes
y sticky match only at exactly lastIndex
d indices report start and end positions of groups

The v flag is the newest (supported in all major browsers since 2023). It allows class tricks such as [\p{L}--[a-z]] (letters except aโ€“z).

JS Flags in action

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A global regex remembers where it stopped. Regex objects with the g or y flag keep a lastIndex property, and test() continues from there. Calling test() twice on the same text can give true then false! Use the g flag only when you really need all matches, or create the regex fresh each time. The next lesson shows this trap in action.

Reading a pattern

Put the pieces together and patterns become readable. Take a simple time format, "09:45" or "23:05":

TEXT
^ ([01]\d | 2[0-3]) : [0-5]\d $
โ”‚  โ””โ”€โ”€โ”€โ”€ hours 00โ€“23 โ”€โ”€โ”€โ”€โ”˜   โ”‚  โ”” minutes 00โ€“59
start                        colon            end

Written as code: /^([01]\d|2[0-3]):[0-5]\d$/. Read any regex the same way: left to right, one piece at a time, asking "which characters can this match, and how many times?"

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does /^\d{3}$/ match?

    ^ and $ anchor the pattern to the whole string, and \d{3} means exactly three digits.
  2. 2. How do you match a literal dot?

    An unescaped . matches any character. A backslash makes it a real dot, as does putting it in a class: [.].
  3. 3. Given the text <a><b>, what does /<.+?>/ match?

    The lazy +? stops at the first >, so the match is <a>. The greedy .+ would have matched the whole string.
  4. 4. Which flag makes ^ and $ match at the start and end of each line?

    m is multiline mode. s (dotAll) is the one that lets . match line breaks.
  5. 5. What does (?:abc) do?

    (?:...) is a non-capturing group: it groups for quantifiers or alternation but doesn't save the text.

Summary

  • A regex describes a text shape. Write it as /pattern/flags or new RegExp("pattern", "flags").
  • Escape special characters with \. Character classes like [a-z], \d, \w and \s match one character from a set.
  • Quantifiers (*, +, ?, {n,m}) control repetition; they are greedy unless followed by ?.
  • Anchors ^, $ and \b match positions โ€” always anchor validation patterns.
  • Parentheses group and capture; (?<name>โ€ฆ) names a group; | means "or".
  • Flags change matching: g all matches, i ignore case, m lines, s dot matches newlines, u/v Unicode.

Next: Regular Expressions in Practice โ€” search, extract, replace and validate real text.