JavaScript Regular Expressions Syntax

***

Access our comprehensive cheat sheet for JavaScript regular expressions syntax. Ideal for developers needing a quick and reliable reference.

JavaScript Regular Expressions Syntax Cheat Sheet

Regular Expressions (RegEx) are patterns used to match character combinations in strings. In JavaScript, regular expressions are objects that can be created using the RegExp constructor or by using a literal notation.

Creating Regular Expressions

Literal Notation

const regex = /pattern/flags;

Constructor Notation

const regex = new RegExp('pattern', 'flags');

Common Flags

  • g: Global search.
  • i: Case-insensitive search.
  • m: Multi-line search.
  • s: Dot matches newline characters (ES2018).
  • u: Unicode; treat a pattern as a sequence of Unicode code points.
  • y: Sticky; matches only from the index indicated by the lastIndex property of this regular expression.

Special Characters

  • .: Matches any single character except newline.
  • \d: Matches any digit (0-9).
  • \D: Matches any non-digit.
  • \w: Matches any word character (alphanumeric & underscore).
  • \W: Matches any non-word character.
  • \s: Matches any whitespace character.
  • \S: Matches any non-whitespace character.
  • \b: Matches a word boundary.
  • \B: Matches a non-word boundary.
  • ^: Matches the beginning of the string or line.
  • $: Matches the end of the string or line.

Quantifiers

  • *: Matches 0 or more occurrences of the preceding element.
  • +: Matches 1 or more occurrences of the preceding element.
  • ?: Matches 0 or 1 occurrence of the preceding element.
  • {n}: Matches exactly n occurrences of the preceding element.
  • {n,}: Matches n or more occurrences of the preceding element.
  • {n,m}: Matches between n and m occurrences of the preceding element.

Character Classes

  • [abc]: Matches any one of the characters a, b, or c.
  • [^abc]: Matches any character except a, b, or c.
  • [a-z]: Matches any character from a to z.
  • [A-Z]: Matches any character from A to Z.
  • [0-9]: Matches any digit from 0 to 9.

Grouping and Alternation

  • (abc): Matches the exact sequence abc.
  • a|b: Matches either a or b.
  • (a|b): Matches either a or b.

Assertions

  • (?=...): Positive lookahead assertion.
  • (?!...): Negative lookahead assertion.
  • (?<=...): Positive lookbehind assertion (ES2018).
  • (?<!...): Negative lookbehind assertion (ES2018).

Escaping Special Characters

Use a backslash (\) to escape special characters.

const regex = /a\+b/; // Matches "a+b"

Using Regular Expressions in JavaScript

test(): Tests for a match in a string. Returns true or false.

const regex = /hello/;
console.log(regex.test('hello world')); // true

exec(): Executes a search for a match in a string. Returns an array of results or null.

const regex = /hello/;
const result = regex.exec('hello world');
console.log(result); // ["hello", index: 0, input: "hello world", groups: undefined]

String Methods with Regular Expressions

  • match(): Returns an array containing all matches or null.

    const str = 'hello world';
    const regex = /o/g;
    console.log(str.match(regex)); // ["o", "o"]
  • matchAll(): Returns an iterator of all results matching a string against a regular expression, including capturing groups.

    const str = 'hello world';
    const regex = /o/g;
    console.log(Array.from(str.matchAll(regex))); // [["o"], ["o"]]
  • replace(): Replaces matches in a string with a replacement.

    const str = 'hello world';
    const regex = /world/;
    console.log(str.replace(regex, 'JavaScript')); // "hello JavaScript"
  • search(): Searches for a match in a string and returns the index of the match.

    const str = 'hello world';
    const regex = /world/;
    console.log(str.search(regex)); // 6
  • split(): Splits a string into an array of substrings.

    const str = 'hello world';
    const regex = /\s/;
    console.log(str.split(regex)); // ["hello", "world"]

Examples

Validate Email

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test('[email protected]')); // true
console.log(emailRegex.test('invalid-email')); // false

Extract Domain from URL

const url = 'https://www.example.com/path';
const domainRegex = /https?:\/\/(www\.)?([^\/]+)/;
const match = url.match(domainRegex);
console.log(match[2]); // "example.com"

Match All Words

const text = 'This is a test.';
const words = text.match(/\b\w+\b/g);
console.log(words); // ["This", "is", "a", "test"]

This cheat sheet provides an overview of JavaScript regular expressions syntax and usage. Regular expressions are a powerful tool for text processing and data validation in JavaScript.