Regular Expressions: A Comprehensive Guide

Regular Expressions

What Are Regular Expressions

A regular expression (regex) is a pattern used to match character combinations in strings. In JavaScript, regular expressions are objects that can be used to perform pattern matching with strings. They are commonly used for tasks such as text validation, search and replace operations, and data extraction.

Common use cases in JavaScript include:

  • Form validation (e.g., ensuring usernames contain only letters, numbers, or underscores)
  • Filtering sensitive content from text
  • Extracting specific parts from strings

For example, a username validation pattern might look like: /^[a-z0-9_-]{3,16}$/

Syntax

Defining Regular Expressions

In JavaScript, there are two ways to define regular expressions. The simpler method uses literal syntax:

let pattern = /expression/

For example:

let regex = /frontend/

Testing for Matches

The test() method checks if a regular expression matches a specified string:

regexObject.test(stringToTest)

Example:

let reg = /frontend/
let str = 'We are all learning frontend development'
console.log(reg.test(str)) // Returns true if matched

The method returns true if a match is found, otherwise false.

Extracting Matches

The exec() method searches a string for a specified pattern and returns the found text as an object:

let reg = /frontend/
let str = 'We are all learning frontend development'
console.log(reg.exec(str)) // Returns an array or null

If a match is found, exec() returns an array with the match, otherwise it returns null.

Metacharacters

Ordinary Characters

Most characters match themselves. These are called ordinary characters, including all letters and digits. They can only match the same character in the string.

Special Characters (Metacharacters)

Special characters have special meanings in regular expressions, providing flexibility and powerful matching capabilities. For example, instead of listing all 26 letters to match any letter, you can use [a-z].

The main categories of metacharacters are:

  1. Boundary characters (indicating position)
  2. Quantifiers (indicating repetition)
  3. Character classes (like \d for digits 0-9)

Boundary Characters

Boundary characters specify positions in the string:

Character Description
^ Matches the beginning of the string
$ Matches the end of the string

When used together (^ and $), they specify exact matches.

Quantifiers

Quantifiers specify how many times a pattern should appear:

Quantifier Description
* Matches zero or more occurrences
+ Matches one or more occurrences
? Matches zero or one occurrence
{n} Matches exactly n occurrences
{n,} Matches n or more occurrences
{n,m} Matches between n and m occurrences

Note: Avoid spaces around the comma in {n,m}.

Character Classes

Character classes match specific sets of characters:

1. Square Brackets [ ]

Matches any single character within the brackets:

console.log(/[abc]/.test('hello')) // true (contains 'a')

2. Ranges with -

The hyphen specifies a range of characters:

console.log(/^[a-z]$/.test('c')) // true

Examples:

  • [a-z] matches any lowercase letter
  • [a-zA-Z] matches any letter (case-insensitive)
  • [0-9] matches any digit

3. Negation with ^

When placed at the beginning of a character class, ^ negates it:

[^a-z] matches any character except lowercase letters.

4. Dot (.)

The dot matches any single character except newline:

console.log(/a.c/.test('abc')) // true

5. Predefined Character Classes

These are shorthand for common character sets:

Character Description
\d Matches any digit (0-9), equivalent to [0-9]
\D Matches any non-digit, equivalent to [^0-9]
\w Matches any word character (letters, digits, underscore), equivalent to [A-Za-z0-9_]
\W Matches any non-word character, equivalent to [^A-Za-z0-9_]
\s Matches any whitespace character (space, tab, newline, etc.)
\S Matches any non-whitespace character

Modifiers

Modifiers alter how a regular expression is interpreted:

Syntax: /expression/modifiers

  • i - Case-insensitive matching
  • g - Global match (find all matches, not just the first)

Examples:

console.log(/a/i.test('a')) // true
console.log(/a/i.test('A')) // true

Replace Method

The replace() method replaces text matching a regular expression:

string.replace(/regex/, 'replacementText')

Tags: javascript regular-expressions pattern-matching regex web-development

Posted on Sat, 19 Sep 2026 16:43:34 +0000 by Shovinus