`RegExp` Object

This article explains the RegExp object.

We will explain the RegExp object with practical examples.

YouTube Video

RegExp Object

What is RegExp?

RegExp (Regular Expression) is an object used to represent string patterns. Unlike simple character comparisons, you can flexibly define 'strings that meet certain conditions.'.

By using a RegExp object, you can perform operations such as searching, validating, extracting, and replacing strings concisely and clearly. It is highly effective for everyday tasks such as form input validation, log analysis, and text formatting. Below are some simple examples of regular expressions.

1const pattern = /abc/;
  • This regular expression checks whether the sequence 'abc' is included.

How to Create Regular Expressions (Two Methods)

There are two types of RegExp syntax: literal notation and constructor notation.

1// Literal notation: pattern and flags are written together
2const literal         = /hello/;
3const literalWithFlag = /hello/i;
4const literalDigits   = /\d+/;
5
6// Constructor notation: pattern and flags are passed separately
7const constructor         = new RegExp("hello");
8const constructorWithFlag = new RegExp("hello", "i");
9const constructorDigits   = new RegExp("\\d+");
  • Literal notation is concise and readable, making it suitable for regular expressions used as constants.. On the other hand, constructor notation is used when you want to build the pattern using variables or determine its contents at runtime.
  • With literal notation, you can intuitively describe both the regular expression and its flags together. In contrast, with constructor notation, you need to specify the pattern and flags separately.
  • In addition, with constructor notation, you pass the regular expression as a string, so backslashes must be escaped twice.

test(): The Most Basic Validation

The RegExp object provides methods for performing evaluations and operations using regular expressions. test() is a method that returns a boolean indicating whether a pattern matches.

1const regex = /JavaScript/;
2
3console.log(regex.test("I love JavaScript")); // true
4console.log(regex.test("I love TypeScript")); // false
  • It is the first method you should learn, and it is ideal for conditional branching or input validation.

match(): Get Matching Results

match() returns an array containing the matched string and detailed information.

1const text = "Version 1.2.3";
2const result = text.match(/\d+\.\d+\.\d+/);
3
4console.log(result[0]); // "1.2.3"
  • match() is more convenient than test() for extraction and parsing processes.

replace(): Replacing Using Regular Expressions

replace() converts the matched part into another string.

1const text = "Hello   World";
2const result = text.replace(/\s+/g, " ");
3
4console.log(result); // "Hello World"
  • You can use it for log formatting or normalizing unnecessary whitespace.

Flags Basics (g, i, m)

You can specify 'flags' in regular expressions. Flags are options that control how a regular expression processes strings according to certain rules. Even with the same pattern, the results can change depending on the flags.

1const text = "apple Apple APPLE";
2const regex = /apple/gi;        // or new RegExp("apple", "gi");
3
4console.log(text.match(regex)); // ["apple", "Apple", "APPLE"]
  • The g (global) flag searches throughout the entire string.
  • The i (ignore case) flag ignores case differences when matching.
1const multilineText = `apple
2banana
3apple`;
4
5const regexM = /^apple/gm;
6
7console.log(multilineText.match(regexM)); // ["apple", "apple"]
  • The m (multiline) flag is used to treat multi-line strings on a per-line basis. With this, ^ and $ operate based on the beginning or end of each line, rather than the entire string.

Character Classes: Combine Multiple Candidates

By using square brackets [], you can define a set of possible characters for a single position.

1const regex = /gr[ae]y/;
2
3console.log(regex.test("gray")); // true
4console.log(regex.test("grey")); // true
  • This is useful for accommodating spelling variations and simple alternatives.

Metacharacters: Common Shortcuts

Metacharacters are symbols that allow you to write commonly used patterns in a shorter form.

1const regex = /\d{4}-\d{2}-\d{2}/;  // or new RegExp("\\d{4}-\\d{2}-\\d{2}");
2
3console.log(regex.test("2025-12-29")); // true
  • \d means a digit, and {n} specifies the number of repetitions.

^ and $: Validate the Entire String

^ and $ represent the start and end of a string.

1const regex = /^\d+$/;
2
3console.log(regex.test("123"));   // true
4console.log(regex.test("123a"));  // false
  • They are important in situations where an exact match is required, such as form inputs.

Grouping and Capturing

By using parentheses (), you can extract partial values.

1const text = "2025/12/29";
2const regex = /(\d{4})\/(\d{2})\/(\d{2})/;
3const [, year, month, day] = text.match(regex);
4
5console.log(year, month, day); // 2025 12 29
  • It is frequently used for breaking down dates and structured strings.

Common Mistakes and Points to Note

Regular expressions are powerful, but they tend to become difficult to read.

1// Hard to read
2const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+$/;
  • If it becomes too complex, you can consider adding comments, splitting expressions, or revising the process itself.

Summary

RegExp is an essential foundational feature in JavaScript for describing string processing simply and accurately. You don't need to learn complex regular expressions from the start; it's important to use basic methods and syntax like test, match, and replace according to your practical needs. If you can treat regular expressions not as 'special knowledge' but as 'tools for organized pattern representation', you will greatly improve the quality and readability of input validation and text processing.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video