JavaScript Regular Expression
A regular expression (regex) is a pattern that describes a set of strings. JavaScript uses regex to search, match, replace, and validate text — like emails, phone numbers, and passwords.
What is a Regular Expression?
A regular expression (regex or RegExp) is a tiny language for describing text patterns. JavaScript supports regex as both a literal /pattern/flags and via the RegExp constructor — useful for search, replace and validation.
Where Regex is Used
Email Validation
Check if a string looks like an email.
Phone Number
Validate digit count, country code.
Search & Highlight
Find words inside a text editor or chat.
Find & Replace
Mass edit text with one expression.
Password Rules
Enforce uppercase, digit, length, special char.
Parsing
Extract dates, IDs or numbers from a paragraph.
Basic Features
- Regex literal:
/abc/. Constructor:new RegExp("abc"). - Flags:
gglobal,iignore case,mmulti-line. - Test:
regex.test(str)returns true / false. - Match:
str.match(regex)returns array or null.
Most Used Regex Symbols
| Symbol | Meaning | Example |
|---|---|---|
| . | Any character | /h.t/ matches hat, hot |
| \d | Any digit (0-9) | /\d+/ |
| \w | Word character | /\w+/ |
| \s | Whitespace | /\s/ |
| ^ | Start of string | /^Hi/ |
| $ | End of string | /end$/ |
| + | One or more | /a+/ |
| * | Zero or more | /ab*/ |
| ? | Optional | /colou?r/ |
| [abc] | Set of chars | /[aeiou]/ |
| {n,m} | Repeat n to m times | /\d{2,4}/ |
| ( | ) | Group / OR | /cat|dog/ |
Regular Expression in JavaScript
A regular expression, also known as Regex, is a sequence of characters used to create a search pattern. In JavaScript, regex is mainly used for validation, searching, replacing, and extracting text from strings.
Overview of Regular Expression
- Pattern Matching: Used to match text patterns inside strings.
- Validation: Used for email, phone number, password, and date checking.
- Text Manipulation: Used to replace or extract specific text.
- Modifiers:
ifor case-insensitive,gfor global search,mfor multiline. - Methods: Common methods are
test(),match(),search(), andreplace().
Your First Regex Program
<script> let str = "12345"; let pattern = /^\d+$/; document.write(pattern.test(str)); </script>
Examples
<script>
var regexDigit = /^\d{10}$/;
document.write(
regexDigit.test("9995484545")
);
</script>
<script>
let email = "hello@pbainst.in";
let re =
/^[\w.-]+@[\w-]+\.[a-z]{2,}$/i;
document.write(re.test(email));
</script>
<script>
let phone = "9876543210";
let re = /^[6-9]\d{9}$/;
document.write(re.test(phone));
</script>
<script>
var dateRegex =
/^([0-3][0-9]-)([0-1][0-2]-)(\d{2})?\d{2}$/;
document.write(
dateRegex.test("01-02-10")
);
</script>
<script> let str = "Order 23 books and 45 pens"; let nums = str.match(/\d+/g); document.write(nums); </script>
<script>
let s = "JavaScript";
document.write(
s.replace(/[aeiou]/gi, "*")
);
</script>
<script>
let pwd = "Abc@1234";
/*
At least:
1 lowercase,
1 uppercase,
1 digit,
1 special character,
minimum 8 characters
*/
let re =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
document.write(re.test(pwd));
</script>
Importance of Regular Expression
- Pattern Matching: Helps search specific formats inside text.
- Data Validation: Useful for validating emails, phone numbers, passwords, and dates.
- Text Manipulation: Helps replace, remove, or modify text patterns.
- Data Extraction: Extracts useful information from large text data.
- Flexibility: Handles simple and complex text processing tasks.
Important Notes
^matches the start of a string.$matches the end of a string.\dmatches digits from 0 to 9.+means one or more occurrences.gfinds all matches, andiignores case.
Conclusion
Regular expressions are powerful tools for searching, validating, extracting, and manipulating text in JavaScript. They are especially useful in forms, search systems, password checks, and text processing.
Important Notes
- Use the
iflag to ignore case. - Use the
gflag to find all matches, not only the first. - Always escape special characters with
\:\.,\?. - Test regex on regex101.com before using in code.
Real-Life Use Cases
Form Validation
Email, phone, PIN, password rules.
Search Filters
Highlight keywords on the page.
Data Cleaning
Strip HTML tags or non-digit characters.
ID Parsing
Extract Aadhaar, PAN, or roll numbers.
Practice Questions
- Validate a 10-digit Indian phone number using regex.
- Check whether a string contains only letters and digits (alphanumeric).
- Count the number of vowels in a string using regex.
- Remove all extra spaces from a sentence using replace().
- Validate a PAN card format like ABCDE1234F.
Frequently Asked Questions
| Question | Answer |
|---|---|
| Q. How do I write a regex in JavaScript? | Use a literal /pattern/flags or new RegExp('pattern','flags'). |
| Q. What does the i flag do? | It makes the pattern case-insensitive. |
| Q. What does match() return? | An array of matches, or null if no match found. |
| Q. Can regex be slow? | Yes, badly written patterns may cause catastrophic backtracking. Keep patterns tight. |
| Q. Is regex enough for HTML parsing? | No — use the DOM API or a parser. Regex is fine for tiny text patterns. |
Conclusion
Regular expressions are a sharp tool for any developer. Once you learn the basic symbols and flags, you can validate, search, and clean strings with a fraction of the code — making your JavaScript apps cleaner and safer.
JavaScript All Chapters
Continue Learning
Previous
Go to 2D Array Chapter