J

JavaScript Handbook

Clean • Professional

Regular Expression Patterns in JavaScript

2 minute

Regular Expression Patterns (RegExp Patterns)

In JavaScript, regular expression (RegExp) patterns define the structure and rules for matching strings. A pattern can include literal characters, metacharacters, character classes, quantifiers, assertions, groups, alternation, and flags to specify exactly what to match and how.

1. Literal Patterns

Literal patterns match exact characters in a string.

const str = "Hello World";
console.log(/Hello/.test(str)); // true
console.log(/World/.test(str)); // true
console.log(/world/.test(str)); // false (case-sensitive)

Case-insensitive matching: Use the i flag.

console.log(/world/i.test(str)); // true

2. Character Classes

Character classes match any one character from a set:

console.log(/[aeiou]/.test("hello")); // true (matches 'e')
console.log(/[0-9]/.test("123"));    // true (matches '1')
console.log(/[^0-9]/.test("123"));   // false (no non-digit)
  • Combine ranges: [a-zA-Z0-9] matches letters or digits.
  • Shorthand classes:
    • \\d → any digit [0-9]
    • \\w → any word character [a-zA-Z0-9_]
    • \\s → any whitespace

Example:

console.log("a1b2".match(/[a-z]\\d/g)); // ["a1", "b2"]

3. Metacharacters

Metacharacters define special matching rules:

MetacharacterMeaning
.Any character except newline
^Start of string/line
$End of string/line
*0 or more repetitions
+1 or more repetitions
?0 or 1 occurrence / non-greedy
()Groups pattern and captures match
[]Character class
{n,m}Repetition between n and m
``

Examples:

const str = "cat or dog";
console.log(/cat|dog/.test(str)); // true
console.log(/c.t/.test("cot"));   // true

4. Quantifiers

Quantifiers specify how many times a part of the pattern repeats:

console.log(/a{2,4}/.test("aaa")); // true (2 to 4 'a')
console.log(/a*/.test(""));        // true (0 or more 'a')
console.log(/a+/.test("a"));       // true (1 or more 'a')
console.log(/a?/.test(""));        // true (0 or 1 'a')

Greedy vs Lazy Matching:

const str2 = "<p>one</p><p>two</p>";
console.log(str2.match(/<p>.*<\\/p>/));   // greedy → matches both paragraphs
console.log(str2.match(/<p>.*?<\\/p>/g)); // lazy → matches each paragraph separately

5. Assertions

Assertions match positions without consuming characters:

AssertionMeaning
\\bWord boundary
\\BNon-word boundary
^Start of string/line
$End of string/line
(?=...)Positive lookahead
(?!...)Negative lookahead
(?<=...)Positive lookbehind
(?<!...)Negative lookbehind

Examples:

console.log(/\\bcat\\b/.test("the cat sat")); // true
console.log(/(?<=\\$)\\d+/.test("$100"));     // true

6. Groups

  • ( … ) → Capturing group for backreferences or replacements
  • (?: … ) → Non-capturing group

Examples:

console.log("abcabc".match(/(abc)\\1/)); // ["abcabc", "abc"]
console.log("abc def".match(/(?:abc) def/)); // ["abc def"]

7. Alternation (OR Operator)

Matches one of multiple patterns:

console.log("cat".match(/cat|dog/)); // ["cat"]

8. Flags

Flags modify how patterns behave:

FlagMeaning
gGlobal search (all matches)
iCase-insensitive
mMultiline (^/$ match lines)
sDot matches newline
uUnicode mode
ySticky match (from current position)

Example:

console.log("Cat cat".match(/cat/gi)); // ["Cat", "cat"]

Practical Examples

Email Validation:

const emailPattern = /^[\\w.-]+@[\\w.-]+\\.\\w+$/;
console.log(emailPattern.test("[email protected]")); // true

Phone Number (XXX-XXX-XXXX):

const phonePattern = /^\\d{3}-\\d{3}-\\d{4}$/;
console.log(phonePattern.test("123-456-7890")); // true

Date Validation (DD/MM/YYYY):

const datePattern = /^\\d{2}\\/\\d{2}\\/\\d{4}$/;
console.log(datePattern.test("13/10/2025")); // true

Extract URLs:

const urlPattern = /https?:\\/\\/[^\\s]+/g;
console.log("Visit <http://example.com>".match(urlPattern)); // ["<http://example.com>"]

Match Repeated Words:

const repeatPattern = /\b(\w+)\b\s+\1\b/;
console.log("hello hello world".match(repeatPattern)); // ["hello hello", "hello"]

 

Article 0 of 0