Logo Wand.Tools

Regular Expression Generator

Intelligently generate and explain regular expressions, supporting various common pattern matching

JavaScript Regular Expressions Tutorial

  # JavaScript Regular Expressions Tutorial (Complete Syntax + Common Examples)
  
  > This article is a complete tutorial for JavaScript Regular Expressions (RegExp), from beginner to advanced. It includes syntax rules, common metacharacters, flags, assertions, groups, greedy vs. lazy matching, and is applicable to front-end development, web scraping, form validation, and other scenarios. It is suitable for beginners and advanced users to learn and reference.
  
  ## Basic Regex Syntax
  
  ### Two Ways to Create a Regular Expression
  
  ```js
  const regex1 = /abc/;             // Literal way
  const regex2 = new RegExp('abc'); // Constructor way

Common Flags

Flag Description
g Global match
i Case-insensitive match
m Multiline match
s Allows . to match newline (ES2018)
u Supports Unicode (ES6)
y Sticky matching (ES6)

Example:

const re = /hello/gi;
const str = 'Hello hello';
console.log(str.match(re)); // ["Hello", "hello"]

Metacharacters and Character Sets

Common Metacharacters

Character Meaning
. Matches any character (except newline)
\d Matches a digit [0-9]
\D Matches a non-digit character
\w Matches a word character (alphanumeric + underscore)
\W Matches a non-word character
\s Matches a whitespace character
\S Matches a non-whitespace character
\b Matches a word boundary
\B Matches a non-word boundary
\\ Matches a backslash

Character Sets and Ranges

/[abc]/     // Matches 'a' or 'b' or 'c'
/[a-z]/     // Matches lowercase letters
/[A-Z]/     // Matches uppercase letters
/[0-9]/     // Matches digits
/[^abc]/    // Matches any character except a, b, or c

Quantifiers (Repetition)

Quantifier Meaning
* Matches the preceding item 0 or more times
+ Matches the preceding item 1 or more times
? Matches the preceding item 0 or 1 time
{n} Matches exactly n times
{n,} Matches at least n times
{n,m} Matches at least n times, at most m times

Example:

/d{4}/.test("2025");       // true
/ab{2,4}c/.test("abbbc");   // true

Grouping and Capturing

/(abc)/         // Capturing group
/(abc){2}/      // Capturing group repeated
/(?:abc)/       // Non-capturing group
/(a)(b)(c)/     // Multiple capturing groups

Extracting matches:

const match = /(hello) (\w+)/.exec("hello world");
console.log(match[1]); // hello
console.log(match[2]); // world

Assertions (Zero-width Assertions)

Positive Lookahead

/\d+(?=px)/     // Matches digits followed by px

Negative Lookahead

/\d+(?!px)/     // Matches digits not followed by px

Lookbehind (ES2018+)

/(?<=\$)\d+/    // Matches digits preceded by $
/(?<!$)\d+/    // Matches digits not preceded by $

Greedy vs. Lazy Matching

Expression Matching Behavior
.* Greedy (as much as possible)
.*? Lazy (as little as possible)

Example:

const str = '<p>text</p><p>more</p>';
const greedy = /<p>.*<\/p>/;
const lazy = /<p>.*?<\/p>/g;

console.log(str.match(greedy)); // ['<p>text</p><p>more</p>']
console.log(str.match(lazy));   // ['<p>text</p>', '<p>more</p>']

Common Use Case Examples

Email Validation

/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,}$/.test("[email protected]");

Mobile Number Validation (Mainland China)

/^1[3-9]\d{9}$/.test("13888888888");

Remove All Whitespace

const cleaned = str.replace(/\s+/g, '');

Extract Domain from URL

const domain = url.match(/https?:\/\/([^\/]+)/)[1];

Regex Method Summary

Method Description
test(str) Tests if string matches
exec(str) Returns match result object (with groups)
str.match(re) Returns all matches (with global flag)
str.replace() Replaces matched content
str.split(re) Splits string using regex
str.search(re) Returns the index of the first match

Conclusion

This tutorial provides a systematic overview of JavaScript Regular Expression syntax and practical application examples, suitable for front-end development, back-end development, text processing, and various other use cases. Mastering regular expressions can greatly improve string processing efficiency.