Regular Expressions in JavaScript with Examples: A Practical Guide
\n\nRegular 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\n1. Basic Syntax and Creating RegExp
\n\nIn 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\nFlags (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
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
2. Main Methods for Working with Regular Expressions
\n\nIn JavaScript, there are several methods that work with RegExp. Let's look at them with practical examples.
\n\n2.1. test() — Checking for a Match
\nThe method returns true or false. Ideal for validation.
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\n2.2. exec() — Search with Details
\nReturns an array with the match and capturing groups. Convenient for extracting data.
\n\nconst 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\n2.3. match() — Search in a String
\nA string method that returns an array of matches. With the g flag — all matches, without — the first match with groups.
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\n2.4. replace() — Text Replacement
\nAllows you to replace matches with a new string. Supports special characters such as $1 for capturing groups.
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