JavaScript Regular Expressions (Regex): Patterns, Flags, Groups and Examples

A regular expression (regex) is a small pattern language for finding and checking text. One line of regex can validate an email, pull every order number out of a log, or check that a URL matches /orders/123. Playwright uses regexes everywhere: toHaveURL(/dashboard/), getByText(/welcome/i), toHaveTitle(/SQA Tools/). In this lesson you will learn to read and write regexes step by step, use them with JavaScript string methods, and avoid the classic traps.

Advertisement

📖 What You’ll Learn: creating regexes with literals and RegExp, test, character classes, quantifiers and greedy versus lazy matching, anchors and word boundaries, flags (g, i, m, s, u, y, d), capturing and named groups, alternation, match, matchAll and exec, replace with groups and functions, split with regex, lookahead and lookbehind, escaping special characters, the lastIndex trap, and regexes in Playwright tests.


🔎 What Is a Regular Expression?

Definition: a regular expression is a pattern that describes a set of strings. JavaScript regexes are objects of type RegExp. You can create one in two ways:

📄 create.js

// 1. Literal: between slashes, with optional flags after the last slash
const orderPattern = /ORD-\d+/;

// 2. Constructor: from a string, useful when the pattern is built at runtime
const word = "checkout";
const dynamic = new RegExp(`${word}-\\d+`, "i");

console.log(orderPattern.test("Your order ORD-451 is ready"));
console.log(orderPattern.test("No order yet"));
console.log(dynamic.test("CHECKOUT-7 failed"), dynamic.source, dynamic.flags);

⌨️ Terminal

node create.js

🖥️ Output

true
false
true checkout-\d+ i
  • regex.test(text) returns true if the pattern is found anywhere in the text.
  • \d means “any digit” and + means “one or more”, so /ORD-\d+/ matches ORD- followed by digits.
  • In the RegExp string form, backslashes must be doubled ("\\d"), because the string itself processes escapes first.

🔤 Character Classes

A character class matches one character from a set:

PatternMatches
.Any character except a line break
\d / \DA digit 0–9 / anything that is not a digit
\w / \WA word character (letter, digit, _) / anything else
\s / \SWhitespace (space, tab, line break) / anything else
[abc]One of a, b or c
[a-z], [A-Z0-9]A range of characters
[^0-9]Any character NOT in the set

📄 classes.js

console.log(/\d\d\d/.test("Room 404"));       // three digits in a row
console.log(/[aeiou]/.test("rhythm"));         // any vowel?
console.log(/^[A-Z]/.test("Playwright"));      // starts with a capital?
console.log("Tel: +91 98765-43210".replace(/\D/g, ""));   // keep only digits
console.log("a1 b2_c3!".match(/\w/g).join(""));

⌨️ Terminal

node classes.js

🖥️ Output

true
false
true
919876543210
a1b2_c3

🔢 Quantifiers: How Many Times

QuantifierMeaningExample
*0 or more/ab*/ matches a, ab, abbb
+1 or more/\d+/ matches 7, 2026
?0 or 1 (optional)/colou?r/ matches color and colour
{n}Exactly n/\d{6}/ a 6-digit PIN code
{n,}n or more/\w{8,}/ 8+ word characters
{n,m}Between n and m/\d{2,4}/ 2 to 4 digits

📄 quantifiers.js

console.log(/^\d{6}$/.test("411001"), /^\d{6}$/.test("41100"));
console.log(/colou?r/.test("color"), /colou?r/.test("colour"));
console.log("Error!!!!".match(/!+/)[0]);

⌨️ Terminal

node quantifiers.js

🖥️ Output

true false
true true
!!!!

Greedy vs lazy

Quantifiers are greedy: they match as much as possible. Adding ? after them makes them lazy: as little as possible.

📄 greedy.js

const html = '<b>Pass</b> and <b>Fail</b>';
console.log(html.match(/<b>.*<\/b>/)[0]);    // greedy: from the first <b> to the last </b>
console.log(html.match(/<b>.*?<\/b>/)[0]);   // lazy: stops at the first </b>

⌨️ Terminal

node greedy.js

🖥️ Output

<b>Pass</b> and <b>Fail</b>
<b>Pass</b>

⚓ Anchors and Word Boundaries

Anchors match a position, not a character:

  • ^: start of the string (or line, with the m flag).
  • $: end of the string (or line, with m).
  • \b: a word boundary, between a word character and a non-word character.

📄 anchors.js

console.log(/\d{4}/.test("abc12345xyz"));      // found somewhere inside
console.log(/^\d{4}$/.test("abc12345xyz"));    // whole string must be 4 digits
console.log(/^\d{4}$/.test("2026"));

console.log(/cat/.test("concatenate"));       // substring match
console.log(/\bcat\b/.test("concatenate"));   // whole word only
console.log(/\bcat\b/.test("the cat sat"));

⌨️ Terminal

node anchors.js

🖥️ Output

true
false
true
true
false
true

⚠️ Watch out: For validation, always anchor the pattern with ^...$. Without anchors, /\d{6}/ also accepts “abc1234567xyz”, because six digits appear somewhere inside it.


Advertisement

🚩 Flags

FlagNameEffect
gglobalFind all matches, not just the first
iignore caseUpper and lower case are equal
mmultiline^ and $ match at each line
sdotAll. also matches line breaks
uunicodeCorrect handling of emoji and Unicode escapes
ystickyMatch only at lastIndex
dindicesReport start/end positions of groups

📄 flags.js

const log = "ERROR db down\nINFO retry\nerror cache miss";

console.log(log.match(/error/g));          // case-sensitive: 1 match
console.log(log.match(/error/gi));         // case-insensitive: 2 matches
console.log(log.match(/^\w+/gm));         // first word of every line
console.log(/down.INFO/.test(log), /down.INFO/s.test(log));   // . and line breaks

⌨️ Terminal

node flags.js

🖥️ Output

[ 'error' ]
[ 'ERROR', 'error' ]
[ 'ERROR', 'INFO', 'error' ]
false true

🎯 Groups, Named Groups and Alternation

Parentheses ( ) create a capturing group. Groups let you extract parts of a match and apply quantifiers to several characters. (?<name>...) creates a named group, and | means “or” (alternation).

📄 groups.js

const line = "Order ORD-2026-451 placed on 2026-11-23 by asha@sqatools.in";

const m = line.match(/ORD-(\d{4})-(\d+)/);
console.log(m[0], "| year:", m[1], "| number:", m[2]);

const date = line.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(date.groups);
const { day, month, year } = date.groups;
console.log(`${day}/${month}/${year}`);

console.log(/^(GET|POST|PUT|DELETE)$/.test("POST"), /^(GET|POST)$/.test("PATCH"));
console.log("hahaha".match(/(ha)+/)[0]);       // quantifier on a group
console.log("2026-11-23".match(/(?:\d+)-(\d+)/)[1]);   // (?:...) groups without capturing

⌨️ Terminal

node groups.js

🖥️ Output

ORD-2026-451 | year: 2026 | number: 451
[Object: null prototype] { year: '2026', month: '11', day: '23' }
23/11/2026
true false
hahaha
11

🧰 Regex Methods: match, matchAll, exec, search

MethodReturns
regex.test(str)true/false
str.match(regex) without gFirst match with groups, or null
str.match(regex) with gArray of all matched strings (no groups), or null
str.matchAll(regex) (needs g)Iterator of every match, each with groups
regex.exec(str)Next match with groups, or null
str.search(regex)Index of the first match, or -1

📄 methods.js

const log = "user=asha status=200 ms=320; user=ravi status=500 ms=1290";

console.log(log.match(/status=\d+/));          // first match + details
console.log(log.match(/status=\d+/g));         // all matches, strings only
console.log("no numbers here".match(/\d+/));   // null when nothing matches

for (const m of log.matchAll(/user=(?<user>\w+) status=(?<status>\d+)/g)) {
  console.log(m.groups.user, m.groups.status);
}
console.log(log.search(/ravi/));

⌨️ Terminal

node methods.js

🖥️ Output

[
  'status=200',
  index: 10,
  input: 'user=asha status=200 ms=320; user=ravi status=500 ms=1290',
  groups: undefined
]
[ 'status=200', 'status=500' ]
null
asha 200
ravi 500
34

⚠️ Watch out: match returns null, not an empty array, when nothing matches. text.match(/\d+/)[0] then throws “Cannot read properties of null”. Use text.match(/\d+/)?.[0] or check for null first.


🔁 replace and split with Regex

In replace, the replacement string can refer to groups with $1, $2 or $<name>. You can also pass a function that computes each replacement.

📄 replace.js

console.log("2026-11-23".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"));
console.log("2026-11-23".replace(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, "$<d>.$<m>.$<y>"));

// Mask every email address in a log line
const log = "Sent to asha@sqatools.in and ravi.k@example.com";
console.log(log.replace(/([\w.]+)@([\w.]+)/g, (match, user, domain) => `${user[0]}***@${domain}`));

// Collapse whitespace and split on several separators
console.log("  Welcome   back \n Asha ".replace(/\s+/g, " ").trim());
console.log("pen, book;lamp | mug".split(/\s*[,;|]\s*/));

⌨️ Terminal

node replace.js

🖥️ Output

23/11/2026
23.11.2026
Sent to a***@sqatools.in and r***@example.com
Welcome back Asha
[ 'pen', 'book', 'lamp', 'mug' ]

Advertisement

👀 Lookahead and Lookbehind

Lookarounds check what comes before or after a position without including it in the match:

SyntaxMeaning
X(?=Y)X followed by Y (positive lookahead)
X(?!Y)X not followed by Y (negative lookahead)
(?<=Y)XX preceded by Y (positive lookbehind)
(?<!Y)XX not preceded by Y (negative lookbehind)

📄 lookaround.js

const prices = "Pen ₹10, Book ₹250, Lamp $40";
console.log(prices.match(/(?<=₹)\d+/g));       // numbers after ₹ only

// Password rule: 8+ characters with at least one digit and one uppercase letter
const strong = /^(?=.*\d)(?=.*[A-Z]).{8,}$/;
for (const pw of ["password", "Password", "Passw0rd", "P0rt"]) {
  console.log(pw.padEnd(9), strong.test(pw));
}

⌨️ Terminal

node lookaround.js

🖥️ Output

[ '10', '250' ]
password  false
Password  false
Passw0rd  true
P0rt      false

⚠️ Special Characters and Common Traps

Escaping special characters

These characters have special meanings and must be escaped with \ to match them literally: . * + ? ^ $ { } ( ) | [ ] \ /.

📄 escape.js

console.log(/sqatools.in/.test("sqatoolsXin"));     // . matches any character!
console.log(/sqatools\.in/.test("sqatoolsXin"));    // escaped: literal dot

// Escape user input before putting it into a RegExp
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const userInput = "price (USD)?";
console.log(new RegExp(escapeRegex(userInput)).test("What is the price (USD)?"));

⌨️ Terminal

node escape.js

🖥️ Output

true
false
true

The g flag and lastIndex trap

A regex with the g or y flag remembers where its last match ended (lastIndex). Reusing the same regex with test() then gives alternating results:

📄 lastindex.js

const hasDigit = /\d/g;
console.log(hasDigit.test("a1"), hasDigit.test("b2"), hasDigit.test("c3"));

const hasDigitFixed = /\d/;   // no g flag for a yes/no check
console.log(hasDigitFixed.test("a1"), hasDigitFixed.test("b2"), hasDigitFixed.test("c3"));

⌨️ Terminal

node lastindex.js

🖥️ Output

true false true
true true true

💡 Tip: Use the g flag only with match, matchAll, replace and replaceAll. For test() checks, leave it off.

Catastrophic backtracking

Nested quantifiers such as /(a+)+$/ can take exponential time on some inputs and freeze a program. Keep patterns simple, avoid nested +/*, and limit input length when validating user data.


🧪 Tester Scenario: Validate and Extract Data

A small validation table checks common formats, and the second part extracts structured data from a log for a report:

📄 validate-extract.js

const rules = {
  email: /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/,
  indianMobile: /^(\+91[- ]?)?[6-9]\d{9}$/,
  pinCode: /^[1-9]\d{5}$/,
  isoDate: /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/,
};

const samples = {
  email: ["qa@sqatools.in", "qa@sqatools", "a b@c.com"],
  indianMobile: ["9876543210", "+91 9876543210", "1234567890"],
  pinCode: ["411001", "011001", "41100"],
  isoDate: ["2026-11-23", "2026-13-01", "2026-02-31"],
};

for (const [rule, values] of Object.entries(samples)) {
  console.log(rule.padEnd(13), values.map((v) => `${v}:${rules[rule].test(v) ? "✓" : "✗"}`).join("  "));
}

const log = `2026-11-23T10:01:02Z GET /api/orders/451 200 320ms
2026-11-23T10:01:05Z POST /api/cart 500 1290ms
2026-11-23T10:01:09Z GET /api/orders/452 200 210ms`;

const requests = [...log.matchAll(/(?<method>GET|POST) (?<path>\S+) (?<status>\d{3}) (?<ms>\d+)ms/g)]
  .map((m) => ({ ...m.groups, status: Number(m.groups.status), ms: Number(m.groups.ms) }));
console.table(requests);
console.log("server errors:", requests.filter((r) => r.status >= 500).map((r) => r.path));

⌨️ Terminal

node validate-extract.js

🖥️ Output

email         qa@sqatools.in:✓  qa@sqatools:✗  a b@c.com:✗
indianMobile  9876543210:✓  +91 9876543210:✓  1234567890:✗
pinCode       411001:✓  011001:✗  41100:✗
isoDate       2026-11-23:✓  2026-13-01:✗  2026-02-31:✓
┌─────────┬────────┬───────────────────┬────────┬──────┐
│ (index) │ method │ path              │ status │ ms   │
├─────────┼────────┼───────────────────┼────────┼──────┤
│ 0       │ 'GET'  │ '/api/orders/451' │ 200    │ 320  │
│ 1       │ 'POST' │ '/api/cart'       │ 500    │ 1290 │
│ 2       │ 'GET'  │ '/api/orders/452' │ 200    │ 210  │
└─────────┴────────┴───────────────────┴────────┴──────┘
server errors: [ '/api/cart' ]

📌 Note: Regex format checks are not full validation: “2026-02-31” passes the date pattern although the date does not exist. Combine a regex with a real check (for example parsing the date) when correctness matters.

In Playwright, the same patterns go straight into assertions, for example:

📄 checkout.spec.js (Playwright, for reference)

await expect(page).toHaveURL(/\/orders\/\d+$/);
await expect(page.getByTestId("order-id")).toHaveText(/^ORD-\d{4}-\d+$/);
await page.getByRole("button", { name: /place order/i }).click();

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Write a regex that checks whether a string is exactly a 4-digit OTP, and test it with "1234", "12a4" and "12345".

Show answer

📄 practice1.js

const otp = /^\d{4}$/;
for (const v of ["1234", "12a4", "12345"]) console.log(v, otp.test(v));

🖥️ Output

1234 true
12a4 false
12345 false

Q2. Extract all numbers from "Order 12 has 3 items costing 450 rupees" as an array of numbers.

Show answer

📄 practice2.js

const text = "Order 12 has 3 items costing 450 rupees";
const numbers = (text.match(/\d+/g) ?? []).map(Number);
console.log(numbers);

🖥️ Output

[ 12, 3, 450 ]

Q3. Check whether a sentence contains the whole word "test" (any case) but not as part of another word. Try "Run the TEST now" and "latest build".

Show answer

📄 practice3.js

const wordTest = /\btest\b/i;
console.log(wordTest.test("Run the TEST now"), wordTest.test("latest build"));

🖥️ Output

true false

Q4. Convert dates from DD/MM/YYYY to YYYY-MM-DD in "Start 05/11/2026, end 23/11/2026".

Show answer

📄 practice4.js

const text = "Start 05/11/2026, end 23/11/2026";
console.log(text.replace(/(\d{2})\/(\d{2})\/(\d{4})/g, "$3-$2-$1"));

🖥️ Output

Start 2026-11-05, end 2026-11-23

Q5. Use named groups to extract the key and value from each key=value pair in "env=qa; browser=firefox; workers=4" into an object.

Show answer

📄 practice5.js

const text = "env=qa; browser=firefox; workers=4";
const config = {};
for (const m of text.matchAll(/(?<key>\w+)=(?<value>\w+)/g)) {
  config[m.groups.key] = m.groups.value;
}
console.log(config);

🖥️ Output

{ env: 'qa', browser: 'firefox', workers: '4' }

Q6. This check gives true, false, true for three valid inputs. Explain and fix it.

const isNumber = /^\d+$/g;
console.log(isNumber.test("10"), isNumber.test("20"), isNumber.test("30"));
Show answer

With the g flag, test starts searching at lastIndex, which is left at the end of the previous match. Remove the g flag:

📄 practice6.js

const isNumber = /^\d+$/;
console.log(isNumber.test("10"), isNumber.test("20"), isNumber.test("30"));

🖥️ Output

true true true

🧠 MCQ Quiz: Regular Expressions

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does \d match?
  2. What does /^abc$/ require?
  3. Which flag makes a regex case-insensitive?
  4. What does "a1b22c333".match(/\d+/g) return?
  5. What does "abc".match(/\d/) return?
  6. How do you match a literal dot?
  7. What is the difference between .* and .*??
  8. In "2026-11-23".replace(/(\d+)-(\d+)-(\d+)/, "$3"), what is the result?
  9. Why can /x/g.test() give different results on repeated calls?
  10. What does (?<year>\d{4}) create?

💼 Interview Questions and Answers

Q1. What is the difference between test(), match() and matchAll()?

regex.test(str) returns a boolean. str.match(regex) without g returns the first match with groups and index; with g it returns an array of matched strings without groups; it returns null if nothing matches. str.matchAll(regex) requires g and returns an iterator of every match with its groups, which is the best choice for extracting structured data.

Q2. How would you validate an email address with a regex, and what are the limits?

A practical pattern is /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/: something without spaces or @, an @, a domain with a dot and a TLD. Fully RFC-compliant email regexes are huge and still cannot prove the mailbox exists. In tests, use a simple pattern for format checks and verify real delivery separately (for example via a test inbox API).

Q3. Explain greedy and lazy quantifiers with an example.

📄 greedy-lazy.js

const s = '"a" and "b"';
console.log(s.match(/".*"/)[0]);
console.log(s.match(/".*?"/)[0]);
console.log(s.match(/"[^"]*"/g));

⌨️ Terminal

node greedy-lazy.js

🖥️ Output

"a" and "b"
"a"
[ '"a"', '"b"' ]

The greedy .* runs to the last quote, swallowing both values. The lazy .*? stops at the first closing quote. A negated class [^"]* is often the clearest and fastest alternative.

Q4. Why might a regex built with new RegExp(userInput) be dangerous?

User input can contain special characters that change the pattern (for example . or (), causing wrong matches or syntax errors, and crafted input can create patterns with catastrophic backtracking that freeze the process (ReDoS). Escape input before building a RegExp, limit input length, and prefer plain string methods such as includes when you do not need a pattern.

Q5. How are regular expressions used in Playwright tests?

Many Playwright APIs accept a RegExp wherever they accept a string: expect(page).toHaveURL(/\/dashboard$/), toHaveTitle(/SQA Tools/), toHaveText(/Order #\d+ confirmed/), getByText(/welcome/i), getByRole("button", { name: /submit/i }) and page.route(/\/api\/orders/). Regexes make assertions tolerant of dynamic parts such as IDs and dates while still checking the structure.


Advertisement

❓ Frequently Asked Questions

🤔 What does /g mean in JavaScript regex?

The global flag: find all matches instead of stopping at the first. It changes what match returns and makes replace replace every match.

🤔 How do I test a regex quickly?

Use the browser console or Node.js REPL with /pattern/.test("text"), or an online tester such as regex101 with the ECMAScript (JavaScript) flavour selected.

🤔 Should I use regex or string methods?

Use string methods (includes, startsWith, split) for fixed text; they are clearer. Use regex for patterns: “digits”, “optional parts”, “any of these words”, and extraction with groups.

🤔 What is the difference between a regex literal and new RegExp()?

A literal (/abc/i) is written directly in code and is checked when the file loads. new RegExp("abc", "i") builds the pattern from a string at runtime, which is needed for dynamic patterns but requires doubled backslashes.


🏁 Summary

  • A regex is a text pattern: create it with /pattern/flags or new RegExp() and check it with test().
  • Character classes (\d \w \s [a-z]), quantifiers (* + ? {n,m}) and anchors (^ $ \b) build most patterns.
  • Flags change behaviour: g all matches, i ignore case, m multiline, s dot matches newlines.
  • Groups and named groups extract parts with match/matchAll, and replace can reuse them.
  • Anchor validation patterns, escape special characters, and do not use g with test().

Next, continue with Lesson 28: Arrays Basics. This completes Module 5 and the Beginner level. Module 6 starts the Intermediate level with arrays.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in