Lesson 80 +15 XP

Regular Expressions

Regular Expressions

A regular expression (RegExp) is a pattern used to search for text. It is written between slashes.

Creating a pattern

let pattern = /hello/;

This pattern matches the text "hello".

Basic usage

/hello/.test("say hello");   // true
/hello/.test("goodbye");     // false

Common methods

  • test(): returns true/false if there is a match.
  • exec(): returns match details or null.
  • match(): string method that returns matches.
"hello world".match(/hello/); // ["hello"]

Flags

Flags come after the closing slash:

FlagMeaning
iignore case
gglobal, find all matches
mmultiline
/hello/i.test("HELLO"); // true

Why use regex?

  • Validate emails, phones, passwords.
  • Search and replace text.
  • Extract parts of strings.

TL;DR

  • RegExp is a text pattern between slashes.
  • test() checks for a match.
  • Flags: i (case), g (all matches), m (multiline).
  • Great for validation and search.