Regular Expressions (RegEx) are patterns used to match, search, or replace characters in
strings. In JavaScript, RegEx is powerful for validating input, searching data, and replacing text.
1. Creating a RegEx Pattern
Two ways to define a RegEx:
const pattern1 = /hello/; // Literal notation
const pattern2 = new RegExp("hello"); // RegExp constructor
2. Basic Methods
Method |
Description |
test() |
Returns true if pattern is
found |
exec() |
Returns match result or null |
match() |
Returns an array of matches |
replace()
|
Replaces matched string |
search() |
Returns index of match or -1 |
split() |
Splits string based on RegEx |
3. Common Patterns & Syntax
Pattern |
Description |
. |
Any character (except newline) |
\d |
Digit (0–9) |
\w |
Word character (a-z, A-Z, 0–9, _) |
\s |
Whitespace |
^ |
Start of string |
$ |
End of string |
+ |
One or more |
* |
Zero or more |
? |
Zero or one |
[abc] |
Match a, b, or c |
(abc) |
Capture group |
` |
` |
4. Example: Validate Email
const email =
"test@example.com";
const pattern = /^[\w.
-]+@[\w.
-]+\.\w+$/;
console.log(pattern.test(email)); // true
5. Example: Extract Numbers
const str = "Price: $100 and $250";
const numbers = str.match(/\d+/g);
console.log(numbers); // ['100', '250']
6. Example: Replace Words
const text = "JavaScript is awesome!";
const newText = text.replace(/awesome/, "powerful");
console.log(newText); // "JavaScript is powerful!"
7. Case-Insensitive & Global Flags
Flag |
Meaning |
g |
Global (match all) |
i |
Case-insensitive |
m |
Multi-line mode |
const sentence = "Hello hello HELLO";
const result = sentence.match(/hello/gi);
console.log(result); // ['Hello', 'hello', 'Hello']
8. Replace All Digits with *1
const input = "My pin is 1234";
const masked = input.replace(/\d/g,"*");
console.log(masked); // "My pin is ****"
Real-World Use Cases
- Form validation (email, phone, password)
- Search and highlight text
- Text processing (cleaning, formatting)
- Data extraction (like numbers or dates)