Regular expressions (regex) are patterns used to match sequences of characters in strings. They are powerful tools for searching, validating, and manipulating text.

Regex patterns are written between slashes (/pattern/).

Syntax: (/pattern/).

Use the RegExp constructor to create a regex.

Syntax: let regex = new RegExp(“hello”);

  • ^: Matches the beginning of a string.
  • $: Matches the end of a string.
JavaScript
let regex = /^hello/; // Matches "hello" only if it’s at the start.
console.log(regex.test("hello world")); // true
console.log(regex.test("world hello")); // false
  • .: Matches any single character except a newline.
  • \d: Matches any digit (0-9).
  • \w: Matches any word character (alphanumeric + underscore).
  • \s: Matches any whitespace character (space, tab).
  • \D, \W, \S: Match the opposite of \d, \w, and \s.
JavaScript
let regex = /\d/; // Matches any digit.
console.log(regex.test("abc123")); // true
  • *: Matches 0 or more occurrences.
  • +: Matches 1 or more occurrences.
  • ?: Matches 0 or 1 occurrence.
  • {n}: Matches exactly n occurrences.
  • {n,}: Matches at least n occurrences.
  • {n,m}: Matches between n and m occurrences.
JavaScript
let regex = /a{2,4}/; // Matches "aa", "aaa", or "aaaa".
console.log(regex.test("aaa")); // true
  • (abc): Matches the exact group abc.
  • [a-z]: Matches any character in the range a to z.
  • [^a-z]: Matches any character NOT in the range a to z.
JavaScript
let regex = /[A-Z]/; // Matches any uppercase letter.
console.log(regex.test("Hello")); // true
  • Use \ to escape special characters like ., *, ?, etc.
JavaScript
let regex = /\./; // Matches a literal dot.
console.log(regex.test("1.23")); // true