Regular Expressions in JavaScript with Examples for Beginners

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

Introduction to JavaScript Regular Expressions

Regular expressions (regex or regexp) are a powerful tool for searching, replacing, and validating strings based on a given pattern. In JavaScript (and Node.js), they are implemented through the built-in RegExp object.

For a beginner, regex syntax may seem intimidating, but it is actually just a language for describing patterns. By mastering the basic constructs, you will be able to:

  • Validate email, phone, URL
  • Extract data from text (parsing)
  • Replace substrings using complex rules
  • Filter and process user input

In this article, we will cover regular expressions in JavaScript with examples on Node.js. All examples can be run in the console or in a runtime environment.



Creating a Regular Expression in JS

In JavaScript, there are two ways to create a regex:

1. Literal syntax (recommended)

const pattern = /hello/;  // Searches for the word "hello"

The pattern is enclosed between two slashes. Flags can be specified after the closing slash (e.g., i — case-insensitive search).



2. RegExp Constructor

const pattern = new RegExp('hello');  // Equivalent to /hello/

Used when the pattern is dynamic (constructed from a variable).



Regular Expression Flags

  • i — ignore case (/hello/i will find "Hello", "HELLO")
  • g — global search (finds all matches, not just the first)
  • m — multiline mode (changes behavior of anchors ^ and $)
  • s — dot matches newline character
  • u — Unicode support
  • y — sticky search (searches only from the lastIndex position)
const regex = /javascript/gi;  // Searches for "javascript" globally and case-insensitively


Key Methods for Working with regex in JavaScript

Let's look at the key methods used with regular expressions.



test() — Checking for a pattern

Returns true or false. The fastest method for validation.

const emailPattern = /^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$/i;console.log(emailPattern.test('user@example.com')); // trueconsole.log(emailPattern.test('invalid-email'));    // false


exec() — Search with details

Returns an array with the match and groups. With the g flag, it remembers the position.

const str = 'Price: 100 rub, discount: 20 rub';const pricePattern = /(\\d+)\\srub/g;let match;while ((match = pricePattern.exec(str)) !== null) {  console.log(`Found: ${match[0]}, number: ${match[1]}`);}// Output:// Found: 100 rub, number: 100// Found: 20 rub, number: 20


match() — Search in a string

A string method. Without the g flag, it returns the first match (like exec). With the g flag, it returns an array of all matches.

const text = 'JS is JavaScript, not to be confused with Java.';const jsMatches = text.match(/Java\\w*/g);console.log(jsMatches); // ['JavaScript', 'Java']


replace() — Pattern-based replacement

Replaces matches with a new string. Supports special characters ($1, $&).

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

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


search() — Index of the first match

const index = 'Hello world'.search(/world/);console.log(index); // 6                

Blogs

Book Recommendations