Fundamentals 17 min read

Comprehensive Guide to Regular Expressions in JavaScript

This article provides a thorough tutorial on regular expressions, covering their history, fundamental concepts like quantifiers and character classes, debugging tools, advanced techniques such as lazy versus greedy matching and assertions, JavaScript RegExp methods, compatibility considerations, and practical code examples for common validation patterns.

政采云技术
政采云技术
政采云技术
Comprehensive Guide to Regular Expressions in JavaScript

Introduction

As a novice programmer, you often rely on search engines to solve complex regular expressions, which can lead to boundary‑value issues and inconsistent team regexes. The best solution is to master regexes and be able to write them by hand.

Why Learn Regular Expressions?

Regular expressions are essential for validating passwords, phone numbers, emails, and other input constraints, as well as for debugging and testing string patterns.

What Is a Regular Expression?

In 1951, mathematician Stephen Kleene introduced the concept of regular expression . Over seventy years later, regexes still influence many aspects of web development.

Typical use cases include matching passwords, phone numbers, emails, or applying input restrictions such as Chinese characters, English letters, or price formats.

How to Test Your Regular Expressions

Built‑in Editor Search

You can use VS Code’s regex search to match content directly in the editor.

Function Calls

Most programming languages provide regex functions for testing patterns.

Online Testing Sites

Tools like Runoob Regex Tester allow you to experiment with patterns quickly.

Fundamentals

Quantifiers

?

The ? quantifier makes the preceding token optional (0 or 1 occurrence).

+

The + quantifier requires at least one occurrence of the preceding token.

*

The * quantifier matches zero or more occurrences.

{...}

The {n} , {n,m} , and {n,} forms specify exact or ranged repetitions.

Grouping (…)

Parentheses group multiple characters together, enabling quantifiers to apply to the whole group.

OR Operator (|)

The pipe character matches either the expression on its left or right.

Character Classes

Square brackets define a set of characters to match, e.g., [0-9] or [a‑z] . Adding ^ inside the brackets negates the set.

Meta Characters

Shorthand tokens like \d , \w , \s , ^ , and $ simplify patterns.

Advanced Concepts

Lazy vs Greedy Matching

Appending ? to a quantifier makes it lazy, causing the engine to match as few characters as possible.

Groups and Backreferences

Non‑capturing groups use (?:…) . Backreferences like \1 refer to previously captured groups.

Assertions (Lookaround)

Positive lookahead (?=…) asserts that a pattern follows, while negative lookahead (?!…) asserts that it does not. Similarly, lookbehind (?<=…) and (?<!…) check the text to the left.

RegExp Methods in JavaScript

test()

Returns true if the pattern matches the string, otherwise false .

exec()

Returns an array with the match details or null if no match is found.

String Methods

match

var str = '2022-04-22';
var reg = /^(\d{4})-(\d{2})-(\d{2})$/;
console.log(str.match(reg));
// ['2022-04-22', '2022', '04', '22', index: 0, input: '2022-04-22', groups: undefined]

replace

var str = '贾维斯:您今天共产生了8个BUG';
var reg = /\w{3}/g;
console.log(str.replace(reg, "Beautiful Code"));
// 贾维斯:您今天共产生了8个Beautiful Code

split

const str1 = '2022-04-21';
const str2 = '2022.04.22';
const str3 = '2022/04/23';
const regsSplit = /[\.\-\/]/;
console.log(str1.split(regsSplit));
console.log(str2.split(regsSplit));
console.log(str3.split(regsSplit));
// ['2022', '04', '21']
// ['2022', '04', '22']
// ['2022', '04', '23']

flags Property

/foo/ig.flags;   // "gi"
/bar/myu.flags;  // "muy"

dotAll (s flag)

The s flag allows . to match newline characters.

console.log(/foo.bar/.test('foo\nbar')); // false
console.log(/foo.bar/s.test('foo\nbar')); // true

Compatibility Notes

Some RegExp methods such as @@split , @@match , @@search , and @@replace are symbols that may have varying support across browsers. Compatibility tables are shown in the original article.

Practical "Dry Goods"

Price Input with Two Decimal Places

// Input restriction
const changePiece = (e) => {
  e.target.value = e.target.value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1');
};
return (
{ changePiece(e) }} />
);

Common Regular Expressions

// Phone number validation
const phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
// ID card validation
const idCardReg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
// URL validation
const urlReg = /^((https?|ftp|file):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
// Email validation
const emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
// Date (YYYY‑MM‑DD) validation
const dateReg = /^\d{4}(\-)\d{1,2}\1\d{1,2}$/;

These examples demonstrate how to apply the concepts discussed throughout the tutorial.

References

Can I Use – Regular Expressions

25 Essential Regular Expressions to Boost Code Efficiency by 80%

10‑Minute Quick Mastery of Regular Expressions (Video)

FrontendJavaScriptRegular ExpressionsregexPattern Matchingstring validation
政采云技术
Written by

政采云技术

ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.