JavaScript Regular Expressions
A regular expression (regex) is a pattern to find or check text. In JavaScript it is written between slashes: /pattern/flags.
const pattern = /cat/;
console.log(pattern.test("The cat sat"));
console.log(pattern.test("The dog sat"));
Output of the above program is
true
false
Flags
| Flag | Meaning |
|---|---|
i | Ignore upper and lower case |
g | Find all matches, not only the first |
m | Multi-line |
Pattern building blocks
| Pattern | Meaning |
|---|---|
. | Any character |
\d, \w, \s | A digit, a word character, a space |
[abc] | One of a, b or c |
[0-9] | A digit |
^, $ | Start and end of the text |
*, +, ? | 0 or more, 1 or more, 0 or 1 |
{3}, {2,4} | Exactly 3, between 2 and 4 |
( ) | A group |
| | Or |
test, match and replace
const text = "Call 98765 or 12345 today";
console.log(/\d{5}/.test(text));
console.log(text.match(/\d{5}/g));
console.log(text.replace(/\d{5}/g, "#####"));
console.log("Hello".match(/l+/)[0]);
Output of the above program is
true
[ "98765", "12345" ]
Call ##### or ##### today
ll
Check a format
const phone = /^[6-9]\d{9}$/; // 10 digit mobile number
console.log(phone.test("9876543210"));
console.log(phone.test("12345"));
const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(email.test("robin@example.com"));
Output of the above program is
true
false
true
Groups
const date = "2025-01-15";
const [, year, month, day] = date.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(year, month, day);
Output of the above program is
2025 01 15
Note:
Regex can look unreadable. Build patterns step by step, and test them in a tool like regex101.com. Do not use a regex to check complicated formats like a full email standard.
Summary
- Patterns go between slashes, with flags like
gandi. test()checks,match()finds,replace()changes.- Anchors
^and$check the whole text. - Related: Forms and Validation.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |