In modern web development, applications frequently need to work with text.
Examples include:
Validating email addresses
Checking phone numbers
Verifying passwords
Searching text
Replacing words
Filtering user input
Imagine creating a registration form.
You need to verify:
Is the email valid?
Is the phone number correct?
Does the password meet requirements?
Writing complex conditions for each validation would be difficult.
To solve this problem, JavaScript provides Regular Expressions (RegEx).
Regular Expressions allow developers to search, match, validate, and manipulate text efficiently.
In this article, we will learn:
What RegEx is
Why RegEx is useful
Creating Regular Expressions
Pattern Matching
Special Characters
Character Classes
Quantifiers
Validation
Search and Replace
Real-world Examples
What is RegEx?
RegEx stands for:
Regular Expression
A Regular Expression is a pattern used to match text.
Think of it as a search rule.
Example:
Find all words containing "Java"
RegEx can perform this task instantly.
Real-Life Example
Suppose a teacher wants to find all students whose names begin with "A".
Without RegEx:
Check every name manually
With RegEx:
Apply Pattern
A*
Matching names are found automatically.
Why RegEx is Important
RegEx helps with:
Validation
Searching
Filtering
Text Processing
Data Cleaning
Almost every website uses RegEx.
Creating a Regular Expression
There are two ways.
Method 1: Literal Notation
let pattern =
/hello/;
Method 2: Constructor
let pattern =
new RegExp("hello");
Both are valid.
Testing a Pattern
The test() method checks whether a match exists.
Example:
let pattern =
/hello/;
console.log(
pattern.test("hello world")
);
Output:
true
Example
let pattern =
/hello/;
console.log(
pattern.test("JavaScript")
);
Output:
false
Because "hello" is not present.
Case Sensitivity
By default:
/hello/
matches:
hello
but not:
HELLO
Ignore Case Flag
Use:
/hello/i
Example:
let pattern =
/hello/i;
console.log(
pattern.test("HELLO")
);
Output:
true
Common Flags
| Flag | Meaning |
|---|---|
| i | Ignore Case |
| g | Global Search |
| m | Multi-line Search |
The match() Method
Used to retrieve matching text.
Example:
let text =
"JavaScript is awesome";
console.log(
text.match(/JavaScript/)
);
Output:
["JavaScript"]
The search() Method
Returns the position of a match.
Example:
let text =
"I love JavaScript";
console.log(
text.search(/JavaScript/)
);
Output:
7
The replace() Method
Replaces matching text.
Example:
let text =
"Hello World";
let result =
text.replace(
/World/,
"JavaScript"
);
console.log(result);
Output:
Hello JavaScript
Character Classes
Character classes define groups of characters.
Digits
\d
Means:
Any digit 0–9
Example:
console.log(
/\d/.test("5")
);
Output:
true
Non-Digits
\D
Means:
Any non-digit character
Word Characters
\w
Matches:
A-Z
a-z
0-9
_
Non-Word Characters
\W
Matches special symbols.
Whitespace
\s
Matches:
Space
Tab
Newline
Non-Whitespace
\S
Matches anything except whitespace.
Character Sets
Example:
/[abc]/
Matches:
a
b
c
Example
console.log(
/[abc]/.test("banana")
);
Output:
true
Because "a" exists.
Range Matching
/[A-Z]/
Matches:
Any uppercase letter
Example
console.log(
/[A-Z]/.test("HELLO")
);
Output:
true
Quantifiers
Quantifiers specify how many times a character should appear.
The * Quantifier
a*
Means:
0 or more a's
Example
Matches:
a
aa
aaa
The + Quantifier
a+
Means:
1 or more a's
Example
Matches:
a
aa
aaa
but not:
(empty)
The ? Quantifier
a?
Means:
0 or 1 occurrence
Exact Quantity
\d{5}
Means:
Exactly 5 digits
Example
console.log(
/\d{5}/.test("12345")
);
Output:
true
Start and End Anchors
Start Anchor
^
Matches beginning.
Example:
/^Hello/
Matches:
Hello World
but not:
World Hello
End Anchor
$
Matches end.
Example:
/World$/
Matches:
Hello World
Email Validation
Basic email pattern:
let emailPattern =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
Example
console.log(
emailPattern.test(
"abc@gmail.com"
)
);
Output:
true
Phone Number Validation
10-digit number:
let phonePattern =
/^\d{10}$/;
Example:
console.log(
phonePattern.test(
"9876543210"
)
);
Output:
true
Password Validation
At least 8 characters:
let passwordPattern =
/^.{8,}$/;
Example:
console.log(
passwordPattern.test(
"mypassword"
)
);
Output:
true
Practical Example – Name Validation
Only alphabets allowed:
let namePattern =
/^[A-Za-z]+$/;
Example:
console.log(
namePattern.test(
"Rahul"
)
);
Output:
true
Global Search
Using:
g
Example:
let text =
"cat dog cat";
console.log(
text.match(/cat/g)
);
Output:
["cat","cat"]
Splitting Text
Example:
let text =
"Apple,Mango,Orange";
let fruits =
text.split(",");
Output:
["Apple","Mango","Orange"]
Practical Project – Email Checker
function validateEmail(email)
{
let pattern =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
}
console.log(
validateEmail(
"test@gmail.com"
)
);
Output:
true
Practical Project – Mobile Number Validator
function validatePhone(phone)
{
let pattern =
/^\d{10}$/;
return pattern.test(phone);
}
console.log(
validatePhone(
"9876543210"
)
);
Output:
true
Common RegEx Patterns
| Purpose | Pattern |
|---|---|
| /^[^\s@]+@[^\s@]+.[^\s@]+$/ | |
| Phone | /^\d{10}$/ |
| Only Letters | /^[A-Za-z]+$/ |
| Only Numbers | /^\d+$/ |
| Password 8+ | /^.{8,}$/ |
Real-Life Applications
RegEx is used in:
Login Forms
Registration Systems
Search Engines
Password Validation
Data Cleaning
Text Editors
Chat Applications
Websites and applications use RegEx daily to validate user input and process text efficiently.
Common Mistakes Beginners Make
Forgetting Escape Characters
Wrong:
/.
/
Correct:
/\./
Missing Anchors
Wrong:
\d{10}
May match inside larger strings.
Correct:
/^\d{10}$/
Using Complex Patterns Too Early
Start with simple patterns and gradually build complex ones.
Advantages of RegEx
Powerful text matching
Fast validation
Compact code
Flexible searching
Essential for web development
Conclusion
Regular Expressions are one of the most powerful tools in JavaScript. They allow developers to search, validate, filter, and manipulate text efficiently.
Comments
Post a Comment