When working with text, sometimes simple string methods aren't enough.
For example, imagine we want to check whether:
An email has a particular format
A phone number contains only digits
A username contains only letters and numbers
A password contains at least one number
A string starts or ends with a particular pattern
Writing separate conditions for every possible pattern can become messy.
This is where Regular Expressions, commonly called RegEx, become useful.
What is a Regular Expression?
A regular expression is a pattern used to search, match, or validate text.
For example:
const pattern = /hello/;
console.log(pattern.test("Hello World"));The result is:
falseWhy? Because regular expressions are case-sensitive by default.
If we use the i flag:
const pattern = /hello/i;
console.log(pattern.test("Hello World"));Output:
trueRegEx might look strange at first, but once you understand the basic symbols, it becomes much easier.
Creating a Regular Expression
There are two common ways to create a regular expression.
Regular Expression Literal
const pattern = /hello/;This is the most common syntax.
RegExp Constructor
const pattern = new RegExp("hello");For most simple cases, the literal syntax is easier to read.
The test() Method
One of the easiest ways to use a regular expression is with test().
It returns true if the pattern matches and false otherwise.
const pattern = /javascript/i;
console.log(pattern.test("I am learning JavaScript"));Output:
trueIf there is no match:
console.log(pattern.test("I am learning Python"));Output:
falseThis makes test() very useful for validation.
Literal Characters
The simplest regular expression just looks for exact text.
const pattern = /cat/;It matches:
catIt can also match inside a larger string:
pattern.test("The cat is sleeping");Result:
trueThe i Flag
The i flag makes the pattern case-insensitive.
const pattern = /javascript/i;
console.log(pattern.test("JavaScript"));
console.log(pattern.test("JAVASCRIPT"));
console.log(pattern.test("javascript"));All three return:
trueWithout i, uppercase and lowercase letters are treated differently.
The g Flag
The g flag means global.
It is useful when we want to find all matches instead of just the first one.
For example:
const pattern = /apple/g;
const text = "apple banana apple mango apple";
console.log(text.match(pattern));Output:
["apple", "apple", "apple"]Character Classes
Regular expressions provide special patterns for matching groups of characters.
[abc]
Matches one character that is either a, b, or c.
const pattern = /[abc]/;
console.log(pattern.test("apple"));Output:
trueThe a matches.
[a-z]
Matches any lowercase letter from a to z.
const pattern = /^[a-z]+$/;
console.log(pattern.test("hello"));Output:
true[A-Z]
Matches uppercase letters.
const pattern = /^[A-Z]+$/;
console.log(pattern.test("HELLO"));[0-9]
Matches digits from 0 to 9.
const pattern = /^[0-9]+$/;
console.log(pattern.test("12345"));Output:
trueUseful Character Shortcuts
JavaScript RegEx provides shortcuts for common character groups.
Pattern | Meaning |
|---|---|
| A digit |
| Not a digit |
| Letter, digit, or underscore |
| Not a word character |
| Whitespace |
| Not whitespace |
| Almost any single character |
For example:
const pattern = /\d/;
console.log(pattern.test("Hello 5"));Output:
trueBecause the string contains a digit.
Quantifiers
Quantifiers tell RegEx how many times something should appear.
+
Means one or more.
const pattern = /\d+/;
console.log(pattern.test("123"));*
Means zero or more.
const pattern = /a*/;?
Means zero or one.
const pattern = /colou?r/;This can match both:
color
colour{n}
Matches exactly n occurrences.
const pattern = /\d{4}/;This matches exactly four digits.
For example:
2026{min,max}
We can specify a range.
const pattern = /\d{2,4}/;This means between 2 and 4 digits.
For example:
12
123
1234Start and End Anchors
Two very useful symbols are:
^
$^
Means the pattern must start at the beginning of the string.
const pattern = /^Hello/;Matches:
Hello WorldBut not:
Hi Hello$
Means the pattern must end at the end of the string.
const pattern = /World$/;Matches:
Hello Worldbut not:
World HelloValidating an Entire String
Combining anchors with character classes is especially useful for validation.
For example, suppose we want a username containing only letters and numbers:
const pattern = /^[a-zA-Z0-9]+$/;
console.log(pattern.test("John123"));Output:
trueBut:
console.log(pattern.test("John@123"));Output:
falseThe @ isn't allowed by our pattern.
Extracting Matches with match()
The match() string method can be used with regular expressions to retrieve matching text.
const text = "I have 10 apples and 20 oranges.";
console.log(text.match(/\d+/g));Output:
["10", "20"]Here:
\d+ → One or more digits
g → Find all matchesReplacing Text with RegEx
Regular expressions can also be used with replace().
For example:
const text = "JavaScript is great. JavaScript is powerful.";
const result = text.replace(/JavaScript/g, "JS");
console.log(result);Output:
JS is great. JS is powerful.The g flag ensures that all matching occurrences are replaced.
We can also use the i flag:
const result = text.replace(/javascript/gi, "JS");Now uppercase and lowercase variations are matched as well.
A Practical Email Validation Example
A common beginner example is checking whether an email has a basic expected format.
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(pattern.test("john@example.com"));Output:
trueAnd:
console.log(pattern.test("john@example"));Output:
falseHowever, don't assume a regular expression can perfectly determine whether an email address is actually valid. Email syntax is more complicated than most simple validation patterns suggest.
For normal web forms, using:
<input type="email">along with appropriate server-side validation is often a better approach.
A Practical Phone Number Example
Suppose we want to check whether a value contains exactly 10 digits:
const pattern = /^\d{10}$/;
console.log(pattern.test("9876543210"));Output:
trueBut:
console.log(pattern.test("98765"));returns:
falseThe pattern means:
^ → Start
\d → Digit
{10} → Exactly 10 times
$ → EndRegular Expressions with Form Validation
RegEx becomes particularly useful when combined with forms.
For example:
const usernamePattern = /^[a-zA-Z0-9_]{3,15}$/;
const username = "john_123";
if (usernamePattern.test(username)) {
console.log("Valid username");
} else {
console.log("Invalid username");
}This pattern allows:
Letters
Numbers
Underscores
Between 3 and 15 characters
This is a practical example of how RegEx can simplify validation logic.
Common RegEx Symbols
Here's a quick reference:
Pattern | Meaning |
|---|---|
| Any character except line terminators |
| Digit |
| Word character |
| Whitespace |
|
|
| Lowercase letter |
| Digit |
| Start of string |
| End of string |
| One or more |
| Zero or more |
| Zero or one |
| Exactly |
| Between |
` | ` |
Conclusion
Regular expressions are a powerful way to search, match, extract, replace, and validate text.
The basic structure looks like:
const pattern = /pattern/;And one of the easiest ways to test it is:
pattern.test("some text");The most important things to learn first are:
\d → Digit
\w → Word character
\s → Whitespace
[abc] → Character choices
+ → One or more
* → Zero or more
? → Optional
{n} → Exact count
^ → Start
$ → End
i → Case-insensitive
g → Global matchingDon't try to memorize every RegEx symbol at once. Start with the common patterns, practice creating small expressions, and use them alongside JavaScript string methods when you need more advanced text processing.