These examples demonstrate JavaScript regex literals, constructor strings, escapes, classes, quantifiers, alternatives, assertions, and Unicode syntax. Each example includes a task, complete code, expected output, and an explanation. Examples using the v flag need a runtime that supports Unicode set notation.
Task: Find a word inside a longer string.
const pattern = /cat/;
console.log(pattern.test("A cat is here."));
console.log(pattern.test("concatenate"));Expected output:
true
true
Explanation: The pattern has no anchors, so it can match cat anywhere in the input, including inside a longer word.
Task: Construct a pattern for one or more digits from a JavaScript string.
const digits = new RegExp("\\d+");
console.log(digits.test("Room 42"));
console.log(digits.test("Room A"));Expected output:
true
false
Explanation: The constructor first receives a JavaScript string. Two backslashes in the source string produce one backslash for the regex parser.
Task: Match a period as punctuation rather than as a wildcard.
const pattern = /a\.b/;
console.log(pattern.test("a.b"));
console.log(pattern.test("a-b"));Expected output:
true
false
Explanation: An unescaped dot is a wildcard. The backslash makes it match a literal period.
Task: Find a slash between two words.
const path = /docs\/chapter/;
console.log(path.test("docs/chapter"));
console.log(path.test("docs-chapter"));Expected output:
true
false
Explanation: The escaped slash is part of the pattern instead of closing the regex literal.
Task: Match a tab between two words.
const pattern = /first\tsecond/;
console.log(pattern.test("first\tsecond"));
console.log(pattern.test("first second"));Expected output:
true
false
Explanation: \t represents a tab character. The ordinary space in the second string is a different character.
Task: Match the two letters represented by their escape sequences.
const pattern = /\x41\u0042/;
console.log(pattern.test("AB"));
console.log(pattern.test("ab"));Expected output:
true
false
Explanation: \x41 represents uppercase A, and \u0042 represents uppercase B.
Task: Match one character between two letters, then observe the line-terminator behavior.
const pattern = /c.t/;
console.log(pattern.test("cat"));
console.log(pattern.test("c-t"));
console.log(pattern.test("c\nt"));Expected output:
true
true
false
Explanation: The dot matches one character other than a line terminator. The dotAll flag, covered in the next chapter, changes this behavior.
Task: Match an uppercase letter from A through F or a digit from zero through three.
const pattern = /[A-F0-3]/;
console.log(pattern.test("B"));
console.log(pattern.test("3"));
console.log(pattern.test("G"));Expected output:
true
true
false
Explanation: A hyphen between class endpoints defines a range. This pattern has two ranges: A-F and 0-3.
Task: Match a literal hyphen or one of the letters from A through C.
const pattern = /[-A-C]/;
console.log(pattern.test("-"));
console.log(pattern.test("B"));
console.log(pattern.test("D"));Expected output:
true
true
false
Explanation: A hyphen at the start of a class is literal. Between two characters, it defines a range.
Task: Check whether a string contains any character that is not an ASCII digit.
const nonDigit = /[^0-9]/;
console.log(nonDigit.test("508"));
console.log(nonDigit.test("50x"));Expected output:
false
true
Explanation: The caret immediately after the opening bracket negates the class. The expression succeeds when it finds one non-digit character.
Task: Check for a digit, a basic word character, and whitespace.
console.log(/\d+/.test("Box 42"));
console.log(/\w+/.test("user_name"));
console.log(/\s/.test("two words"));Expected output:
true
true
true
Explanation: \d matches ASCII digits, \w matches the basic word-character set, and \s matches whitespace.
Task: Find exactly four consecutive digits in a larger input.
const fourDigits = /\d{4}/;
console.log(fourDigits.test("Room 2048"));
console.log(fourDigits.test("Room 208"));Expected output:
true
false
Explanation: The bounded quantifier requires four consecutive digits. Without anchors, those digits can be part of a larger string.
Task: Match both common spellings, with and without the letter u.
const color = /colou?r/;
console.log(color.test("color"));
console.log(color.test("colour"));
console.log(color.test("colouur"));Expected output:
true
true
false
Explanation: The question mark applies only to the preceding u, making that one character optional.
Task: Accept either of two beverage names.
const beverage = /tea|coffee/;
console.log(beverage.test("tea break"));
console.log(beverage.test("coffee break"));
console.log(beverage.test("water break"));Expected output:
true
true
false
Explanation: The vertical bar separates alternatives. Either alternative can produce a match.
Task: Match exactly the text cat.
const wholeInput = /^cat$/;
console.log(wholeInput.test("cat"));
console.log(wholeInput.test("a cat"));Expected output:
true
false
Explanation: ^ asserts the start position and $ asserts the end position. For strict validation, account for the special behavior of $ before a final line terminator.
Task: Compare an input with and without a trailing line feed.
const fourDigits = /^\d{4}$/;
console.log(fourDigits.test("2048"));
console.log(fourDigits.test("2048\n"));Expected output:
true
true
Explanation: Without multiline mode, $ can match at the end of the input or just before a final line terminator. If a format must reject a trailing newline, use a validation strategy that explicitly checks the complete input.
Task: Find cat as a whole word, not as part of concatenate.
const wholeWord = /\bcat\b/;
console.log(wholeWord.test("a cat sleeps"));
console.log(wholeWord.test("concatenate"));Expected output:
true
false
Explanation: \b asserts a boundary between a basic word character and a non-word character. It does not consume the surrounding characters.
Task: Compare how much text greedy and lazy quantifiers consume.
const text = "<b>one</b><i>two</i>";
console.log(text.match(/<.*>/)[0]);
console.log(text.match(/<.*?>/)[0]);Expected output:
<b>one</b><i>two</i>
<b>
Explanation: The greedy pattern consumes through the last available closing angle bracket. The lazy pattern tries the shortest match that lets the pattern finish, so it stops at the first one.
Task: Match consecutive letters from a Unicode string.
const letters = /\p{Letter}+/u;
console.log("café7".match(letters)[0]);
console.log("Καλημέρα".match(letters)[0]);Expected output:
café
Καλημέρα
Explanation: The Unicode property escape \p{Letter} matches letters across scripts. Unicode-aware mode is required. The digit ends the first match.
Task: Match an emoji by its Unicode code point.
const smile = /\u{1F600}/u;
console.log(smile.test("😀"));
console.log(smile.test("A"));Expected output:
true
false
Explanation: The braced code point escape is used with Unicode-aware mode. It can represent characters outside the Basic Multilingual Plane.
Task: Match characters that are both letters and Greek script characters.
const greekLetters = /[\p{Letter}&&\p{Script=Greek}]+/v;
console.log(greekLetters.test("Καλημέρα"));
console.log(greekLetters.test("hello"));Expected output in a runtime that supports the v flag:
true
false
Explanation: The v flag enables set operations in character classes. The intersection operator && requires a character to belong to both properties. The u and v flags cannot be used together.
Task: Handle a malformed character class.
try {
new RegExp("[");
console.log("valid");
} catch (error) {
console.log(error instanceof SyntaxError);
}Expected output:
true
Explanation: An opening bracket starts a character class. Since this pattern has no valid closing bracket, constructing it throws a SyntaxError.
Task: Require a letter or underscore first, followed by zero or more basic word characters.
const identifier = /^[A-Za-z_]\w*$/;
console.log(identifier.test("_item42"));
console.log(identifier.test("42item"));
console.log(identifier.test("item-name"));Expected output:
true
false
false
Explanation: The first character class excludes digits and hyphens. Later characters can include digits because \w includes them. This is a teaching pattern, not the complete JavaScript identifier grammar.
Task: See the effect of adding anchors.
const search = /\d{3}/;
const complete = /^\d{3}$/;
console.log(search.test("Order 204"));
console.log(complete.test("Order 204"));
console.log(complete.test("204"));Expected output:
true
false
true
Explanation: The first pattern can find three digits anywhere. The second requires the entire input to satisfy the pattern, subject to the end assertion's final-line-terminator behavior.
Task: Match a boundary outside a class and a backspace inside a class.
const boundary = /\bcat\b/;
const backspace = /[\b]/;
console.log(boundary.test("a cat"));
console.log(backspace.test("\b"));Expected output:
true
true
Explanation: Outside a character class, \b is a zero-width word-boundary assertion. Inside a class, it denotes the backspace character.
Task: Use a simple tag-shaped pattern to find the first tag.
const text = "<b>one</b><i>two</i>";
const firstTag = /<[^<>]*>/;
console.log(text.match(firstTag)[0]);Expected output:
<b>
Explanation: The negated class stops at the next angle bracket. This can illustrate delimiters in simple text, but HTML has nested structure, quoted attributes, comments, and other rules that require an HTML parser for general processing.
- Does the pattern search for a substring or require the whole input?
- Are special characters escaped when they should be literal?
- Does each quantifier repeat the intended atom?
- Does the dot's line-terminator behavior fit the task?
- Does the shorthand character class fit the text's writing systems?
- Does the pattern need Unicode-aware mode?
- Could an ambiguous pattern backtrack excessively?
- Have trailing line terminators and malformed input been considered?
| Previous chapter | Chapter lesson | Chapter Q&A | Next chapter |
|---|---|---|---|
| 71 - SharedArrayBuffer, Atomics, and shared memory | Open lesson | Open Q&A | 73 - RegExp groups, flags, and string methods |