Regular Expressions in JavaScript with Examples for Node.js
Regular expressions (regex or regexp) are a powerful tool for searching, replacing, and extracting text information. In JavaScript and Node.js, they are used everywhere: from form validation to log parsing and request processing. This article will help you master regular expression syntax with practical examples that you can run immediately in Node.js.
1. Creating Regular Expressions in JavaScript
In JavaScript, there are two ways to create a regular expression:
- Literal syntax — the pattern is enclosed in slashes
/pattern/flags. Recommended for static patterns. - RegExp constructor —
new RegExp('pattern', 'flags'). Used if the pattern is formed dynamically.
// Literal methodconst regexLiteral = /hello/i;
// RegExp constructorconst pattern = 'hello';const regexConstructor = new RegExp(pattern, 'i');
console.log(regexLiteral.test('Hello World')); // trueconsole.log(regexConstructor.test('Hello World')); // true2. Basic Methods for Working with Regular Expressions
In Node.js and browsers, four key methods are available for working with regex. Let's examine each with examples.
The test() method
Checks whether the string contains a match to the pattern. Returns true or false.
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;console.log(emailPattern.test('user@example.com')); // trueconsole.log(emailPattern.test('invalid-email')); // falseThe exec() method
Searches for a match and returns an array with details (the match itself, groups, index, input string). If there are no matches — null.
const text = 'Price: 1500 rubles, discount: 300 rubles';const regex = /(\\d+)\\srubles/g;let match;
while ((match = regex.exec(text)) !== null) { console.log(`Found: ${match[1]} rubles`); // Output: "Found: 1500 rubles" // Output: "Found: 300 rubles"}The match() method
Called on a string. Returns an array of matches (with the g flag) or detailed information (without the g flag).
const logLine = 'Error 404: page not found';const errorRegex = /(\\d{3}):\\s(.+)/;const result = logLine.match(errorRegex);
console.log(result[0]); // '404: page not found'console.log(result[1]); // '404'console.log(result[2]); // 'page not found'The replace() method
Replaces matches with a specified string or the result of a function. Great for data formatting.
const phone = '+7 (999) 123-45-67';const cleanPhone = phone.replace(/[\\s\\-\\(\\)\\+]/g, '');console.log(cleanPhone); // '79991234567'
// Replacement using groupsconst date = '2024-01-15';const formattedDate = date.replace(/(\\d{4})-(\\d{2})-(\\d{2})/, '$3.$2.$1');console.log(formattedDate); // '15.01.2024'3. Basic Characters and Flags of Regular Expressions
To work effectively with regex, you need to understand the basic metacharacters and flags. Here are the key ones:
Search Characters
.— any character (except newline)\\d— digit (0-9)\\w— letter, digit, or underscore\\s— whitespace character^— start of string$— end of string*— 0 or more repetitions+— 1 or more repetitions?— 0 or 1 repetition{n,m}— from n to m repetitions
Flags
g— global search (all matches)