Master JavaScript Regular Expressions: From Basics to Advanced Patterns
An in‑depth JavaScript regular‑expression guide walks you through creating patterns, using modifiers, character classes, anchors, quantifiers, greedy vs lazy matching, capturing and named groups, assertions, and essential string methods, complete with practical code snippets and tips for testing regex online.
Getting Started
Two useful online regex testers are recommended: regex101.com and jex.im/regulex . A regular expression consists of a pattern and optional flags. You can create a RegExp object using the longer syntax: regexp = new RegExp("pattern", "flags"); Or the shorter slash syntax:
regexp = /pattern/; // no flags
regexp = /pattern/gmi; // flags g, m, iThe slash tells JavaScript that a regular expression is being defined, similar to how quotes denote a string.
Modifiers
i– case‑insensitive matching g – global (match all occurrences) u – Unicode matching, e.g.,
/\p{...}/u m– multiline, where ^ and $ match line starts and ends
let regexp = /\p{sc=Han}/gu; // match Chinese characters
let str = `Hello Привет 你好 123_456`;
alert(str.match(regexp)); // 你,好Character Classes
\d– digit \s – whitespace \w – word character (letters, digits, underscore)
These can be combined:
let str = "test ES 6 AA";
let reg = /e\w\s\d/i;
str.match(reg); // ["ES 6", index: 6, input: "test ES 6 AA"]Each class also has a negated form ( \D, \S, \W).
let str = "+7(903)-123-45-67";
alert(str.replace(/\D/g, "")); // 79031234567Anchors ^ $
^xx– matches at the start of a string xx$ – matches at the end of a string
const time = "12:02";
let reg = /^\d\d:\d\d$/;
reg.test(time); // trueEscaped Characters
The characters [ \ ^ $ . | ? * + ( ) must be escaped when used literally.
Sets and Ranges [...]
[abc]– matches any of a, b, or c [a-z], [1-5] – matches a range [^abcd] – matches any character except a, b, c, d (used for exclusion)
Alternation |
The pipe works like an OR operator: gr(a|e)y matches gray or
grey gra|eymatches gra or
eyQuantifiers * + ?
*– 0 or more + – 1 or more ? – 0 or 1 (same as {0,1}) {n} – exactly n {2,5} – between 2 and 5 {3,} – 3 or more
Greedy vs Lazy Modes
Greedy quantifiers match as much as possible, causing backtracking when the overall pattern fails:
let str = `"hi" some word "ok" aa`;
let reg = /".+"/g;
str.match(reg); // ["hi" some word "ok"]Adding ? makes the quantifier lazy, stopping at the first satisfactory match:
let str = `123 456`;
let reg1 = /\d+ \d+?/;
let reg2 = /\d+ \d+/;
str.match(reg1); // 123 4
str.match(reg2); // 123 456Capturing Groups (...)
Groups
Parentheses capture matched substrings as a whole:
let str = "gogogoaa";
let reg = /(go)+/;
str.match(reg); // gogogoNested Groups
let str = `<group1 group2>`;
let arr = str.match(/<((\w+)\s(\w+))>/);
console.log(arr[0]); // <group1 group2>
console.log(arr[1]); // group1 group2
console.log(arr[2]); // group1
console.log(arr[3]); // group2matchAll with the g flag
let str = `<group1> <group2>`;
let arr = Array.from(str.matchAll(/<(group\d)>/g));
// arr[0][0] => <group1>, arr[0][1] => group1
// arr[1][0] => <group2>, arr[1][1] => group2Named Groups ?<name>
let regexp = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/g;
let str = "2019-10-30, 2020-01-01";
alert(str.replace(regexp, '$<day>.$<month>.$<year>'));
// 30.10.2019, 01.01.2020Replacing Capturing Groups
let str = "John Bull";
let regexp = /(\w+) (\w+)/;
alert(str.replace(regexp, '$2, $1')); // Bull, JohnBackreferences
let str = `He said: "She's the one!".`;
let regexp = /(['"])(.*?)\1/g;
alert(str.match(regexp)); // "She's the one!" let regexp = /(?<g1>['"])(.*?)\k<g1>/g;
alert(str.match(regexp)); // "She's the one!"Assertions
Lookahead Assertions
let str = "1 turkey costs 30€";
alert(str.match(/\d+(?=€)/)); // 30Lookbehind Assertions
let str = "1 turkey costs 30€";
let reg = /\d+(?=(€|kr))/;
alert(str.match(reg)); // 30, €Assertions are zero‑width; they assert a condition without consuming characters.
String and RegExp Methods
str.match(regexp)– returns matches str.matchAll(regexp) – returns an iterator of all matches with groups str.split(regexp|substr, limit) – splits the string str.search(regexp) – index of first match or -1 str.replace(regexp|substr, replacement) – replace matches regexp.exec(str) – executes regexp and returns result array regexp.test(str) – true if a match exists
References
The Modern JavaScript Tutorial.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
WeDoctor Frontend Technology
Official WeDoctor Group frontend public account, sharing original tech articles, events, job postings, and occasional daily updates from our tech team.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
