Regular Expressions in JavaScript with Examples: A Practical Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Regular Expressions in JavaScript with Examples: A Practical Guide

\n\n

Regular expressions (RegExp) are a powerful tool for searching, replacing, and validating text. In JavaScript, especially in the Node.js environment, they are used everywhere: from parsing logs to validating forms. In this article, we will break down the syntax, methods, and write practical examples that you can immediately use in your projects.

\n\n

1. Basic Syntax and Creating RegExp

\n\n

In JavaScript, a regular expression can be created in two ways: a literal and a constructor. The literal is convenient for static patterns, the constructor for dynamic ones.

\n\n
// Literal (recommended)\nconst regexLiteral = /hello/gi;\n\n// Constructor (for dynamic patterns)\nconst pattern = "hello";\nconst flags = "gi";\nconst regexConstructor = new RegExp(pattern, flags);
\n\n

Flags (modifiers):

\n
    \n
  • g — global search (finds all matches, not just the first)
  • \n
  • i — case-insensitive search
  • \n
  • m — multiline mode (anchors ^ and $ work for each line)
  • \n
  • s — allows the dot . to match the newline character
  • \n
  • u — enables full Unicode support
  • \n
\n\n

Basic metacharacters:

\n
    \n
  • . — any character except newline
  • \n
  • \\d — digit (0-9)
  • \n
  • \\w — letter, digit, or underscore
  • \n
  • \\s — whitespace character (space, tab, newline)
  • \n
  • ^ — start of string
  • \n
  • $ — end of string
  • \n
  • [] — character class (e.g. [a-z] — all lowercase letters)
  • \n
  • () — capturing group
  • \n
  • | — logical OR
  • \n
\n\n

2. Main Methods for Working with Regular Expressions

\n\n

In JavaScript, there are several methods that work with RegExp. Let's look at them with practical examples.

\n\n

2.1. test() — Checking for a Match

\n

The method returns true or false. Ideal for validation.

\n\n
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\nconst emails = ["user@example.com", "invalid-email", "test@domain.co.uk"];\n\nemails.forEach(email => {\n  console.log(`${email}: ${emailPattern.test(email)}`);\n});\n// user@example.com: true\n// invalid-email: false\n// test@domain.co.uk: true
\n\n

2.2. exec() — Search with Details

\n

Returns an array with the match and capturing groups. Convenient for extracting data.

\n\n
const logLine = "ERROR: 2023-10-15 14:30:00 - Server crash";\nconst logPattern = /^(ERROR|WARN|INFO): (\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) - (.+)$/;\nconst result = logPattern.exec(logLine);\n\nif (result) {\n  console.log(`Level: ${result[1]}`);\n  console.log(`Date: ${result[2]}`);\n  console.log(`Message: ${result[3]}`);\n}\n// Level: ERROR\n// Date: 2023-10-15 14:30:00\n// Message: Server crash
\n\n

2.3. match() — Search in a String

\n

A string method that returns an array of matches. With the g flag — all matches, without — the first match with groups.

\n\n
const text = "Tel: +7(999)123-45-67, +7(495)765-43-21";\nconst phonePattern = /\\+7\\(\\d{3}\\)\\d{3}-\\d{2}-\\d{2}/g;\nconst phones = text.match(phonePattern);\n\nconsole.log(phones);\n// ['+7(999)123-45-67', '+7(495)765-43-21']
\n\n

2.4. replace() — Text Replacement

\n

Allows you to replace matches with a new string. Supports special characters such as $1 for capturing groups.

\n\n
const messyDate = "2023/10/15";\nconst cleanDate = messyDate.replace(/(\\d{4})\\/(\\d{2})\\/(\\d{2})/, "$3.$2.$1");\nconsole.log(cleanDate); // 15.10.2023\n\n                

Blogs

Book Recommendations