Reading Time 3
Number of Words 551
Regular expressions (often called “regex” or “regexp”) are patterns used to match character combinations in strings. They’re extremely powerful for validating input, searching and replacing text, extracting data, and more.
Table of Contents
- What Is a Regular Expression?
- Creating Regular Expressions
- Basic Pattern Syntax
- Flags / Modifiers
- Common Tasks & Examples
- Testing & Tools
- Tips & Best Practices
1. What Is a Regular Expression?
A regex is a sequence of characters defining a search pattern. In JavaScript, regexes are represented using either literal notation or via the RegExp constructor. These allow you to test, match, and manipulate text with flexible rules.
2. Creating Regular Expressions
Two ways to define regexes in JS:
- Literal syntax:
const pattern = /abc/; - Constructor syntax:
const pattern2 = new RegExp('abc');
The literal version is more concise and commonly used, but the constructor is useful when patterns are dynamic (built from strings).
3. Basic Pattern Syntax
Here are some core components of regex syntax:
| Syntax | Description | Example |
|---|---|---|
. |
Matches any single character except newline | /a.c/ matches “abc”, “aoc”, “a-c” |
^ |
Start of string | /^Hello/ matches “Hello world” but not “Well Hello” |
$ |
End of string | /end$/ matches “The end” but not “The end is near” |
[] |
Character set / class | /[aeiou]/ matches any vowel |
[^ ] |
Negated character set | /[^aeiou]/ matches any non-vowel |
* |
0 or more repetitions | /fo*/ matches “f”, “fo”, “foo”, “fooo” |
+ |
1 or more repetitions | /fo+/ matches “fo”, “foo”, etc., but not “f” alone |
? |
0 or 1 repetition; also used for non-greedy or optional parts | /colou?r/ matches “color” or “colour” |
{m,n} |
Between m and n repetitions | /a{2,4}/ matches “aa”, “aaa”, or “aaaa” |
| ` | ` | Alternation (“or”) |
() |
Grouping / capture | /(abc)+/ matches one or more “abc” sequences |
4. Flags / Modifiers
Flags are placed after the closing slash (or passed via constructor) to modify how the pattern behaves:
g— global search (find all matches)i— case-insensitive matchingm— multi-line modeu— Unicode; treat pattern as Unicode with full UTF-16 supports— “dotAll” mode; dot.matches newline as welly— sticky matching (match starting exactly at current position)
5. Common Tasks & Examples
Example 1: Validate an Email Address
function isValidEmail(email) {
const re = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
return re.test(email);
}
console.log(isValidEmail('john.doe@example.com')); // true
console.log(isValidEmail('invalid-email@.com')); // false
Example 2: Replace Multiple Spaces with Single Space
const text = 'This is a sentence with extra spaces.';
const cleaned = text.replace(/\s+/g, ' ');
console.log(cleaned); // “This is a sentence with extra spaces.”
Example 3: Extract All Numbers From a String
const str = 'Order 123: 4 items at $5 each';
const numbers = str.match(/\d+/g);
console.log(numbers); // ["123", "4", "5"]
Example 4: Split on Comma or Semicolon
const data = 'apple,banana;cherry,dragonfruit;eggfruit';
const parts = data.split(/[,;]+/);
console.log(parts); // ["apple", "banana", "cherry", "dragonfruit", "eggfruit"]
Example 5: Capture Groups & Retrieving Matches
const date = '2025-10-11';
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
if (match) {
const [full, year, month, day] = match;
console.log(year, month, day); // "2025" "10" "11"
}
6. Testing & Tools
- Use Regex101, RegExr, or Regexper to build and test your patterns interactively.
- In browser dev tools, try simple patterns in the Console to experiment.
- Use the
String.prototype.match(),replace(),search(),split()methods in JS for applying regexes.
7. Tips & Best Practices
- Always escape special characters like
.,*,?,+,^,$,/,\, etc. when they’re meant literally. - Prefer using raw strings (regex literals) when possible; they improve readability.
- Keep regexes simple. If they become too complex, consider breaking tasks into smaller steps or using string operations.
- Use the right flags. For example, to handle non-ASCII characters properly, use
u. - Be cautious with greedy vs non-greedy quantifiers (e.g.,
.*vs.*?). - When matching user input, test edge cases (empty strings, weird characters, long input).