Regular Expressions in JavaScript with Examples: In Practice

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: In Practice



Regular expressions (RegExp) are a powerful tool for searching, replacing, and validating strings. In JavaScript and Node.js, they are used everywhere: from form validation to log parsing. In this article, we will cover the basics of syntax, popular methods, and solve several practical tasks.



1. Creating a Regular Expression



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



  • Literal notation (recommended): /pattern/flags
  • Constructor new RegExp('pattern', 'flags')


Example:



// Literal notationconst regexLiteral = /hello/i;

// Constructor (useful when the pattern is dynamic)const pattern = 'hello';const regexConstructor = new RegExp(pattern, 'i');

console.log(regexLiteral.test('Hello World')); // trueconsole.log(regexConstructor.test('HELLO')); // true


2. Basic RegExp and String Methods



To work with regular expressions in JavaScript, two types of methods are used: methods of the RegExp object itself and string methods.



2.1 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'));    // false


2.2 The exec() Method

Searches for a match and returns an array with detailed information (or null). Useful for extracting data.



const str = 'Price: 1500 rubles, discount: 200 rubles';const priceRegex = /(\\d+)/g;let match;

while ((match = priceRegex.exec(str)) !== null) { console.log(`Found number: ${match[1]}`);}// Output:// Found number: 1500// Found number: 200


2.3 The String match() Method

Works similarly to exec(), but is called on the string.



const text = 'JavaScript is cool! JS is used everywhere.';const result = text.match(/JS/g);console.log(result); // [ 'JS', 'JS' ]


2.4 The String replace() Method

Replaces found matches with the specified string or the result of a function.



const phone = '+7 (123) 456-78-90';const cleaned = phone.replace(/[\\s\\-\\(\\)\\+]/g, '');console.log(cleaned); // 71234567890

// Replacement using capture groupsconst date = '2024-03-15';const formatted = date.replace(/(\\d{4})-(\\d{2})-(\\d{2})/, '$3.$2.$1');console.log(formatted); // 15.03.2024


2.5 The String search() Method

Returns the index of the first match or -1.



const sentence = 'Learn JavaScript at PythonLib';const index = sentence.search(/javascript/i);console.log(index); // 6


3. Flags and Special Characters: Practical Examples



Flags change the search behavior. The most popular ones:

  • g — global search (finds all matches, not just the first).
  • i — case-insensitive search.
  • m — multiline mode (anchors ^ and $ work on each line).


Example with the m flag:



const multiLineText = `First linesecond lineThird line`;

// Without the m flagconsole.log(multiLineText.match(/^second/)); // null

// With the m flagconsole.log(multiLineText.match(/^second/m)); // [ 'second' ]


Basic Special Characters



Blogs

Book Recommendations

Character Description