⚡ JavaScript

JavaScript (Node.js) 中的正则表达式:详细指南

What is it and why? (a real-life analogy)

Imagine you are a librarian in a huge library with millions of books. A reader comes to you and says: "Find me all the books that have the word 'adventures' in the title, but only those written after 2000, and with a dragon picture on the cover." Without special tools, you would have to go through each book manually — it would take weeks.

Regular Expressions (or regexp for short) are exactly that kind of magical tool for searching text. Only instead of books, we search in strings (text), and instead of verbal descriptions, we use a special pattern language.

Here's another analogy. Imagine you want to find all the apples in a basket of fruit. You could go through each fruit by hand — that's slow. Or you could say: "Give me all the round ones, red or green, fist-sized." That's a regular expression — a description of what you're looking for, in a special language.

Important: Regular expressions are not a JavaScript-specific feature. They exist in almost all programming languages: Python, Java, C++, PHP, and even in text editors like VS Code or Notepad++. But the syntax may differ slightly.

In programming, regular expressions are used for:

  • Input validation — for example, checking if a string is an email address or a phone number
  • Searching — finding all dates in a text, all links, all mentions of something
  • Replacement — replacing all "cat" with "dog", but only if it's a whole word
  • Splitting — breaking a string into parts based on a complex pattern

In Node.js (JavaScript on the server), regular expressions are especially useful for processing data from the internet, parsing HTML pages, form validation, and working with databases.

Theory: how it works internally

To understand how regular expressions work, you need to imagine we have a string of text and a "search automaton." This automaton moves through the string character by character and checks whether the current section matches our pattern.

A regular expression consists of ordinary characters (which search for themselves) and special characters (metacharacters) that have a special meaning.

Basic concepts

Pattern — this is what we are searching for. For example, the pattern cat will find all occurrences of "cat" in the string.

Flags — these are search settings. For example, the flag i makes the search case-insensitive (it will search for "Cat", "cat", and "CAT").

Methods — these are ways to apply a regular expression to a string. In JavaScript, there are several methods: test(), exec(), match(), replace(), search(), split().

How the regex engine processes text

Imagine we have the string "The cat sat on the mat" and the pattern /cat/. The engine does the following:

  1. Starts at the first position (character 'T')
  2. Checks if 'T' matches 'c' — no, move on
  3. Checks 'h' against 'c' — no
  4. Checks 'e' against 'c' — no
  5. Checks space against 'c' — no
  6. Checks 'c' against 'c' — yes! Check the next character
  7. 'a' against 'a' — yes! Check the next one
  8. 't' against 't' — yes! Found a match!

If we were searching for /c.t/ (where the dot is any character), then in steps 6-8 we would find "cat", but we would also find "cot" if it existed, or "c!t".

It's important to understand: Regular expressions search for the first match by default. If you need to find all matches, use the g (global) flag.

Syntax in JavaScript (Node.js): all forms and variants

In JavaScript, there are two ways to create a regular expression:

1. Literal syntax (most common)

// Pattern is enclosed in slashes, flags after the second slash
const regexp = /pattern/flags;

// Example: find the word "hello" case-insensitively
const regexp1 = /hello/i;

2. RegExp constructor (when the pattern is dynamic)

// First argument is a string with the pattern, second is a string with flags
const regexp = new RegExp('pattern', 'flags');

// Example: find a word that comes from a variable
const searchWord = 'hello';
const regexp2 = new RegExp(searchWord, 'i');

Flags table

Flag Name Description Example
g Global Finds all matches, not just the first one /cat/g finds all "cat"
i Case-insensitive Ignores letter case /cat/i finds "Cat", "CAT", "cat"
m Multiline Multiline mode. Anchors ^ and $ work for each line /^hello/m finds "hello" at the start of each line
s Dotall The dot . now includes the newline character /hello.world/s finds "hello world"
u Unicode Enables full Unicode support (emojis, Cyrillic) /p{Emoji}/u finds all emojis
y Sticky Search only