Regular Expressions in JavaScript: A Complete Guide with Examples
Regular expressions (regexp or regex) are a powerful tool for searching, replacing, and validating text data. In JavaScript, especially in a Node.js environment, regular expressions are used everywhere: from log processing and URL parsing to form validation and text markup. In this article, we will break down the basics of working with regular expressions in JavaScript, examine the syntax, methods, and provide practical examples for Node.js.
Creating Regular Expressions in JavaScript
In JavaScript, there are two ways to create a regular expression:
- Literal notation — the most convenient and common way:
/pattern/flags. - RegExp constructor — used when the pattern is created dynamically:
new RegExp('pattern', 'flags').
Examples:
// Literal notationconst regexLiteral = /hello/i; // flag i — case-insensitive
// RegExp constructorconst pattern = 'hello';const regexConstructor = new RegExp(pattern, 'i');
console.log(regexLiteral.test('Hello, world!')); // trueconsole.log(regexConstructor.test('HELLO')); // trueBasic Flags (Modifiers)
i— case-insensitive matching.g— global search (finds all matches, not just the first).m— multiline mode (anchors^and$work for each line).s— "dotall" mode (dot.includes the newline character).u— full Unicode support.y— "sticky" mode (search from the current position).
Regular Expression Methods in JavaScript
In JavaScript, regular expressions work together with several string methods and the RegExp object itself.
The test() Method
Checks if there is a match in the string. Returns true or false.
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;console.log(emailRegex.test('user@example.com')); // trueconsole.log(emailRegex.test('invalid-email')); // falseThe exec() Method
Performs a search and returns an array with results or null. Useful for extracting groups.
const urlRegex = /https?:\\/\\/([^\\/]+)\\/(.*)/;const url = 'https://pythonlib.ru/regular-expressions';const match = urlRegex.exec(url);
if (match) { console.log('Domain:', match[1]); // pythonlib.ru console.log('Path:', match[2]); // regular-expressions}String Methods Working with regexp
str.match(regex)— returns an array of matches (ornull).str.matchAll(regex)— returns an iterator of all matches (with groups).str.replace(regex, replacement)— replaces matches.str.search(regex)— returns the index of the first match (-1 if none).str.split(regex)— splits a string by a regular expression.
const text = 'Code: 12345, article: ABC-6789';
// match — find all digitsconst numbers = text.match(/\\d+/g);console.log(numbers); // ['12345', '6789']
// replace — replace hyphen with colonconst cleaned = text.replace(/-/g, ':');console.log(cleaned); // 'Code: 12345, article: ABC:6789'
// split — split by commas and spacesconst parts = text.split(/,\\s*/);console.log(parts); // ['Code: 12345', 'article: ABC-6789']Basic Patterns and Special Characters
Metacharacters and quantifiers are used to create precise patterns. Here are the most important ones:
Basic Characters
- <