JavaScript RegExp
JavaScript RegExp
A Regular Expression (RegExp) in JavaScript is a pattern used to search, match, and manipulate text. It helps validate data like email, phone numbers, passwords, etc.
You can create a RegExp in two ways:
RegExp Methods
✔ test() — Returns true or false
✔ exec() — Returns match details or null
✔ String Methods with RegExp
| Method | Description | Example |
|---|---|---|
match() |
Finds matches | "Hello".match(/l/g) |
replace() |
Replace matched text | "Hello".replace(/l/g, "*") |
search() |
Returns first match index | "Hello".search(/e/) |
split() |
Split using regex | "a,b;c".split(/[,;]/) |
Example:
RegExp Modifiers (Flags)
| Flag | Meaning | Example |
|---|---|---|
g |
Global search | /a/g |
i |
Case-insensitive | /apple/i |
m |
Multi-line | /^hello/m |
Example:
RegExp Special Characters
| Symbol | Meaning | Example |
|---|---|---|
. |
Any character | /h.t/ → “hat”, “hot” |
^ |
Begins with | /^hello/ |
$ |
Ends with | /world$/ |
\d |
Digits 0–9 | /\d/ |
\w |
Alphanumeric | /\w/ |
\s |
Whitespace | /\s/ |
+ |
One or more | /a+/ |
* |
Zero or more | /a*/ |
{n} |
Exact count | /\d{3}/ → 3 digits |
|
OR |
Useful Examples
✔ Validate Email
✔ Validate Phone Number (Indian Example)
✔ Strong Password Check
Summary
| Feature | Example |
|---|---|
| Create RegExp | /pattern/ |
| Test text | regex.test(text) |
| Search & replace | text.replace(regex, value) |
| Validate input | Emails, phone numbers, passwords |
