Regex, short for Regular Expression, is a powerful tool used in JavaScript and many other programming languages to search, match, and manipulate strings based on specific text patterns.

💡 Key Idea
Think of regex as a specialized search tool that can find complex combinations of characters, not just exact words.
Regex patterns are made up of characters and special symbols that define the rules for matching text. This allows you to:
- Check if a string contains a certain pattern
- Extract parts of a string that match a pattern
- Replace or split strings based on patterns
| Symbol | Meaning |
|---|---|
| . | Matches any single character except newline |
| * | Matches zero or more occurrences of the preceding element |
| + | Matches one or more occurrences of the preceding element |
| ? | Makes the preceding element optional (zero or one occurrence) |
| ^ | Matches the start of a string |
| $ | Matches the end of a string |
| [abc] | Matches any one character inside the brackets (a, b or c) |
| \d | Matches any digit (0-9) |
| \w | Matches any word character (letters, digits, underscore) |
| \s | Matches any whitespace character (space, tab, newline) |
💡 Regex in JavaScript
Regex patterns are created using either /pattern/flags syntax or by using the RegExp constructor.
📌 Deep Dive: Simple Regex Test
const pattern = /cat/;
console.log(pattern.test("I have a cat.")); // true
console.log(pattern.test("I have a dog.")); // false
false
Here, the regex /cat/ looks for the substring "cat" anywhere in the text.
⚠️ Important
Regex can be tricky—small changes in a pattern can drastically change what it matches. Always test your regex carefully.
Regex is a fundamental skill that helps automate many text-processing tasks efficiently.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does regex primarily help with in JavaScript?
Question 2 of 2
Which symbol in regex matches any digit from 0 to 9?
Loading results...