Regular Expressions in JavaScript

Regular expressions or regex are versatile tools for pattern matching and text manipulation. JavaScript provides native support for regex through the RegExp object and built-in string methods, enabling efficient validation, parsing, and text processing.



What You’re Going to Learn

You’ll learn the basics of regular expressions using JavaScript — including how to write patterns, use common symbols, and apply them with built-in methods like match, test, and replace.


What Is a Regular Expression?

A regular expression (or regex) is a special pattern of characters used to search, match, or manipulate text. Instead of scanning strings manually, you can describe what you're looking for using precise patterns — whether it's digits, email addresses, dates, or specific word formats.

JavaScript natively supports regular expressions through the RegExp object and string methods like match(), test(), and replace().

Here's a basic example: searching for the word "hello" in a string.

javascript
// Look for the word 'hello' in a string
const regex = /hello/;
const text = 'hello world';

if (regex.test(text)) {
  console.log("Found it!");
}

🔍 How It Works

  • /hello/: A regular expression pattern that looks for the word "hello".
  • test(): A method that checks if the pattern exists in the string and returns true or false.
  • regex: The regular expression object storing your pattern.
  • text: The string you're searching within.
  • console.log("Found it!"): This runs only if the pattern is found.

Output:

Found it!

This example shows just how easy it is to start using regex in JavaScript — and how powerful it can be for finding patterns in text.


Basic Patterns

These are some essential regex characters you'll frequently use in JavaScript:

PatternMeaning & Examples
.
Matches any character
Pattern
a.c
Matched
"abc", "a1c"
Not Matched
"ac", "abbc"
^
Matches start of a line
Pattern
^a
Matched
"apple", "ace"
Not Matched
"maple", "bacon"
$
Matches end of a line
Pattern
e$
Matched
"apple", "toe"
Not Matched
"each", "top"
*
Matches 0 or more times
Pattern
lo*
Matched
"loooop", "lp", "l"
Not Matched
"snap", "pop"
+
Matches 1 or more times
Pattern
lo+
Matched
"loop", "loo"
Not Matched
"lip", "lap"
?
Matches 0 or 1 time
Pattern
colou?r
Matched
"color", "colour"
Not Matched
"colouur", "colr"
{n}
Matches exactly n times
Pattern
a3
Matched
"aaa"
Not Matched
"aa", "aaaa"
{n,}
Matches at least n times
Pattern
a{2,}
Matched
"aa", "aaa", "aaaaa"
Not Matched
"a", "b"
{n,m}
Matches between n and m times
Pattern
a{2,4}
Matched
"aa", "aaa", "aaaa"
Not Matched
"a", "aaaaa"
[ae]
Matches one character inside brackets
Pattern
[ae]
Matched
"a", "e"
Not Matched
"o", "i"
|
Matches one pattern OR another
Pattern
cat|dog
Matched
"cat", "dog"
Not Matched
"bat", "cow"
()
Groups pattern
Pattern
(ab)+
Matched
"ab", "abab"
Not Matched
"acac", "aba"
\d
Matches any digit (0–9)
Pattern
\d
Matched
"5", "0"
Not Matched
"x", "a"
\D
Matches non-digit
Pattern
\D
Matched
"x", "@"
Not Matched
"8", "5"
\w
Matches letter, number, or _
Pattern
\w
Matched
"a", "5", "_"
Not Matched
"@", "!"
\W
Matches non-word character
Pattern
\W
Matched
" ", "@", "!"
Not Matched
"a", "5"
\s
Matches space, tab, or newline
Pattern
\s
Matched
" ", "\t", "\n"
Not Matched
"x", "a"
\S
Matches non-space character
Pattern
\S
Matched
"x", "a", "5"
Not Matched
" ", "\t"
\b
Matches word boundary
Pattern
\bcat
Matched
"cat food", "the cat"
Not Matched
"concatenate", "educate"
\B
Matches NOT a word boundary
Pattern
\Bcat
Matched
"concatenate", "educate"
Not Matched
"cat food", "the cat"

Basic Regex Methods:

JavaScript provides several built-in methods to work with regular expressions. These methods allow you to test, search, match, and manipulate strings based on patterns. Understanding these methods is key to effectively using regex in real-world applications like form validation, data extraction, and string replacement.

MethodDetails
test()
Tests if pattern exists in string. Returns true/false.
Example: /a/.test('apple')true
exec()
Executes regex and returns first match or null.
Example: /\d+/.exec('Item 123')['123']
match()
Returns result of matching string against regex.
Example: 'abc123'.match(/\d+/)['123']
matchAll()
Returns iterator for all matches (with capture groups).
Example: [...'abc123xyz456'.matchAll(/\d+/g)][['123'], ['456']]
replace()
Replaces first match with replacement string.
Example: 'hello 123'.replace(/\d+/, '456')'hello 456'
replaceAll()
Replaces all matches with replacement.
Example: '1,2,3'.replaceAll(/\d/g, 'x')'x,x,x'
search()
Returns index of first match or -1.
Example: 'hello123'.search(/\d/)5
split()
Splits string by regex pattern.
Example: 'a,b;c'.split(/[;,]/)['a', 'b', 'c']

Regex Flags in JavaScript

Flags modify how a regular expression behaves. They are added after the closing slash, like /pattern/g. Here's a breakdown of the most commonly used flags:

FlagMeaning, Pattern & Matched Examples
g
Meaning: Global — find all matches
Pattern: /a/g
Matched: "aab", "banana" → ["a", "a"], ["a", "a", "a"]
i
Meaning: Ignore case — match upper/lowercase letters equally
Pattern: /hello/i
Matched: "HELLO", "HeLLo world"
m
Meaning: Multiline — Makes ^ and $ match the start and end of each line, not just the whole string.
Pattern: /^hi/m
Matched: "hi\nbye", "hello\nhi there"
s
Meaning: DotAll — dot . matches newline too
Pattern: /a.b/s
Matched: "a\nb", "a b"
u
Meaning: Unicode — matches Unicode characters
Pattern: /\u{1F600}/u
Matched: "😀", "say 😀 again"
y
Meaning: Sticky — matches at exact position (respects lastIndex)
Pattern: /a/y (with lastIndex = 1)
Matched: "ba", "caa" (when lastIndex = 1)

Example: Validating an Email Address

You can use a regular expression in JavaScript to check whether a string is a valid email format. The test method is used with a regex pattern to return true or false.

javascript
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const email = "user@example.com";

if (emailPattern.test(email)) {
  console.log("Valid email address");
} else {
  console.log("Invalid email address");
}

How It Works:

  • /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/: A regex pattern that checks for a valid email structure — text before and after @ and a . in the domain part.
  • test(): A method that checks whether the string matches the pattern and returns a boolean.
  • "user@example.com": This is the input string we’re validating.
  • If the string matches the pattern, "Valid email address" is printed; otherwise, it prints "Invalid email address".

Output

Valid email address

Example 2: Extracting Numbers from a String

Regular expressions can help pull specific patterns out of a string. Here, we’ll extract all the numbers from a string using the match method with a global digit pattern.

javascript
const message = "Order 123: shipped on 2024-06-14.";
const numbers = message.match(/\d+/g);

console.log(numbers);

How It Works:

  • \d+: Matches one or more digits in a row.
  • g: The global flag returns all matches in the string, not just the first.
  • match(): Searches the string for matches and returns them in an array.
  • "Order 123: shipped on 2024-06-14.": The original string to search within.

Output

["123", "2024", "06", "14"]

Example 3: Replacing Spaces with Dashes

Regular expressions make it easy to replace patterns across a string. In this example, we’ll replace all spaces in a sentence with dashes using the replace method and a regex with the global flag.

javascript
const sentence = "JavaScript is powerful";
const slug = sentence.replace(/\s+/g, "-");

console.log(slug);

How It Works:

  • \\s+: Matches one or more whitespace characters (spaces, tabs, etc.).
  • g: Global flag ensures all matches are replaced, not just the first one.
  • replace(): Replaces the matched pattern with a specified string — in this case, "-".
  • slug: The final formatted string with dashes instead of spaces.

Output

JavaScript-is-powerful

Frequently Asked Questions

What is a regular expression in JavaScript?

A regular expression (regex) in JavaScript is a sequence of characters used to define a search pattern. It's commonly used for pattern matching and text validation.


How do you create a regex pattern in JavaScript?

You can create a regex using either regex literals, like /pattern/, or the RegExp constructor, like new RegExp('pattern').


What methods use regular expressions in JavaScript?

Methods like test(), exec(), match(), search(), replace(), and split() can all use regular expressions to work with strings in JavaScript.


Can regex be used for input validation?

Yes, regular expressions are widely used to validate inputs such as email addresses, phone numbers, zip codes, and passwords in JavaScript.


What do the symbols like ^, $, and \d mean in regex?

These are metacharacters: ^ matches the beginning of a string, $ matches the end, and \d matches any digit. They help define specific matching rules in regex patterns.



What's Next?

Next you’ll dive into JavaScript iterators — essential tools for traversing and managing collections of data efficiently.