Home/Blog/Programming/What is Regex? JavaScript regular expressions in 5 minutes
Regex JavaScript Tutorial
Home/Blog/Programming/What is Regex? JavaScript regular expressions in 5 minutes

What is Regex? JavaScript regular expressions in 5 minutes

14 min read
May 06, 2025
content
What is regex?
Core regex syntax in JavaScript
Regex flags and modifiers
JavaScript regex methods
Real-world examples
Example 1: Searching for text with test()
Example 2: Extracting matches with match()
Example 3: Replacing text dynamically with replace()
Example 4: Extracting complex data with exec()
Example 5: Email validation
Example 6: Password validation
Example 7: Extracting URLs
Example 8: Phone number formatting
Example 9: Extracting hashtag
Regex best practices
Wrapping up and next steps

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Key takeaways:

  • Regular expressions are powerful patterns for matching text. They are used widely in tasks such as validating inputs, searching, replacing, and text manipulation across many programming languages.

  • JavaScript supports PCRE-style regular expressions using the native RegExp object. Regex patterns can be created using either the literal syntax (/pattern/flags) or the constructor syntax (new RegExp('pattern', 'flags')), allowing for both static and dynamic patterns.

  • Essential components include start/end characters, flags (e.g., g for global search, i for case-insensitivity), character classes (e.g., [a-z], \w), capturing/non-capturing groups, and quantifiers (+, *) to define matching criteria.

  • The test() method checks for pattern matches and returns true or false, while the exec() method returns an array of matched groups, making it useful for extracting detailed matching information.

If you’ve ever searched for a specific word in a document or replaced a typo in multiple files at once, you’ve already used a basic form of pattern matching. But what if you needed to extract all email addresses from a web page, validate a phone number, or transform text dynamically?

This is where regular expressions (regex) come in.

Regex in JavaScript is a powerful tool for searching, matching, and manipulating text using patterns. While it might look intimidating at first (a mix of cryptic symbols and letters), regex can save you hours of manual work once you understand the basics. In JavaScript, Regex is implemented using the built-in RegExp object, making it easy to create, test, and manipulate text patterns.

JavaScript Regular Expressions in Detail

Cover
JavaScript Regular Expressions in Detail

Regular Expressions, also known as Regex, come in handy in a multitude of text processing scenarios. Regex defines a search pattern using symbols and allows you to find matches within strings. The applications of this span from software engineering to data science and beyond. In this course, you will begin with an introduction to regex, its history, and various types of regular expressions. You will then learn how to create your own regular expressions using various techniques and special characters. In the latter half of the course, you will explore RegExp Objects, how to parse data, turn phrases into an array of strings, and lastly password and email pattern matching. By the end of this course, you will be a regular expressions expert.

3hrs
Beginner
14 Playgrounds
3 Quizzes

In this blog, we’ll break down regex in JavaScript with practical examples so you can use it effectively in real-world applications.

What is regex?#

A regex is a sequence of characters that defines a search pattern. It’s used to:

  • Validate input (e.g., check if a password meets complexity rules).

  • Extract data (e.g., pull dates from a log file).

  • Search and replace text (e.g., reformat phone numbers).

In JavaScript, regex is created in two ways: using literal notation (/pattern/) or the RegExp constructor:

  • Literal notation: /pattern/flags This is the most common way. For example, the following pattern /hello/i matches a string containing "hello" (case-insensitive due to the i flag).

// Literal notation
const regex = /hello/i; // Case-insensitive match for "hello"
  • Constructor notation: new RegExp('pattern', 'flags') Useful when building the regex dynamically. new RegExp("hello") is equivalent to /hello/ in literal notation.

// Constructor
const pattern = "hello"; // Defining pattern
const regex = new RegExp(pattern, "i"); // Case-insensitive pattern match

Note: One big difference between these approaches is that the constructor notation allows a quoted expression to be passed. This allows us to make dynamic expressions. The literal syntax uses forward slashes (/pattern/). The constructor syntax uses quotes ("pattern").

Core regex syntax in JavaScript#

Regular expressions (regex) in JavaScript use a combination of special characters and symbols to match patterns in strings. Below is a categorized list of different regex components:

  • Character classes: Allow you to match specific sets of characters, such as \d (digits), \w (word characters), \s (whitespace), \D (non-digits), \W (non-word characters), and \S (non-whitespace).

  • Quantifiers: Define how often a character or group appears, including * (0 or more), + (1 or more), ? (0 or 1), {n} (exactly n times), {n,} (at least n times), and {n,m} (between n and m times).

  • Anchors: Specify where the match should occur, such as ^ (start of a string), $ (end of a string), \b (word boundary), and \B (non-word boundary).

  • Groups and capturing: Parentheses () in a regex create capturing groups. They serve two main purposes:

    • Grouping: They group parts of a regex, allowing you to apply quantifiers (like *, +, {n}) to the entire group. For example, (ab){3} matches “ababab” because it groups “ab” and applies the quantifier {3} (meaning “three times”).

    • Capturing: They capture the matched text, which can be accessed later (e.g., in the replacement string of a replace operation or through the match result object). For example, to extract all the URLs from a web page, the regex like (https?://\S+) can capture all the URLs.

  • Alternation (OR): Match one pattern or another using | (e.g., apple|orange matches either “apple” or “orange”).

  • Lookaheads and lookbehinds: Lookaheads and lookbehinds are zero-width assertions. They check for a pattern without actually consuming the characters in the string. They are used to match based on what follows or precedes a certain point in the string.

    • Positive lookahead (?=...): Asserts that the pattern following the current position matches. For example, the pattern \w+(?=\d) matches “word” in “word123”.

    • Negative lookahead (?!...): Asserts that the pattern following the current position does not match. For example, the pattern \w+(?!\d) matches “word” in “wordABC” but not “word123”.

    • Positive lookbehind (?<=...): Asserts that the pattern preceding the current position matches. For example, the pattern (?<=\$)\d+ matches “123” in “$123”.

    • Negative lookbehind (?<!...): Asserts that the pattern preceding the current position does not match. For example, (?<!\$)\d+ matches “123” in “123$” but not “123” in “$123”.

  • Escape characters: Match special characters using \ (e.g., \. matches a literal dot, \$ matches a dollar sign).

Before diving into examples, let’s break down some frequently used regex symbols:

Symbol

Meaning

Example Match

\d

Matches any digit (0-9)

"123" in "Age: 123"

\w

Matches word characters (A-Z, a-z, 0-9, _)

"hello" in "hello_123"

\s

Matches any whitespace (space, tab, newline)

" " in "Hello World"

.

Matches any character except the new line

"a.c" → Matches "abc", "a_c"

*

Matches the preceding character zero or more times

a* → Matches "", "a", "aa", "aaaa", etc.

+

Matches the preceding character one or more times

a+ → Matches "a", "aa", "aaa", etc.

?

Matches the preceding character zero or one-time

colou+r → Matches "color", "colour"

^

Matches the beginning of a string

"^Hello""Hello World"

$

Matches the end of the string

"World$""Hello World"

[]

Matches one of the characters inside

"[aeiou]" → Matches any vowel

()

Groups a part of the regex

"(hello)+" → Matches "hello" once or more

Forgetting anchors can lead to partial matches. For example, /\d+/ matches "123" in "abc123xyz," but /^\d+$/ ensures the entire string is numeric.

Regex flags and modifiers#

The flags are optional and modify the behavior of the regex. Common flags include:

  • i: Case-insensitive matching

  • g: Global matching (finds all matches, not just the first)

  • m: Multiline matching (treats each line as a separate string)

JavaScript regex methods#

JavaScript supports many regex methods. Let’s discuss them.

  • test(): Checks if a string contains a match. It returns true or false. /\d+/.test("123") returns true.

  • exec(): Returns an array with information about the first match (or null if no match). It is useful for capturing groups.

  • match(): Returns an array of all matches (or null if no match). It behaves differently with and without the g flag.

  • replace(): Replaces matched patterns with a new string. "hello world".replace(/world/, "JavaScript") returns hello JavaScript.

  • search(): Returns the index of the first match (or -1 if no match).

Real-world examples#

Regular expressions are widely used in various programming and data-processing tasks. Here are some common real-world applications:

  • Form validation: Ensuring emails, passwords, and phone numbers follow the correct formats.

  • Data parsing: Extracting useful data from logs, web pages, and structured text.

  • Search and replace: Modifying or cleaning large text files efficiently.

Let’s discuss some practical examples of using regex.

Example 1: Searching for text with test()#

The test() method is the simplest way to check whether a string pattern exists. It can be used for checking if user input contains specific words (e.g., “password” in a signup form).

Javascript (babel-node)
const regex = /javascript/i; // Case-insensitive search
console.log(regex.test("I love JavaScript!")); // true
console.log(regex.test("I love Python!")); // false

In the code above:

  • Line 1: We declare a constant variable named regex and assign it a regular expression. The pattern /javascript/ looks for the word “javascript.” The i flag stands for “case-insensitive.” This means the regex will match “javascript,” “JavaScript,” “JAVASCRIPT,” or any other variation of the word regardless of capitalization.

  • Lines 2–3: We use the test() method of the regular expression object. The test() method checks if a given string contains a match for the regular expression and returns true if a match is found and false otherwise.

Example 2: Extracting matches with match()#

The match() method returns an array of all pattern occurrences only when the g (global) flag is used. Without the g flag,  it returns a match object containing only information about the first match. When using the g flag, this method can extract all URLs, hashtags, or specific words from a document.

Javascript (babel-node)
const text = "JavaScript is awesome! I love JavaScript.";
const regex = /javascript/gi;
console.log(text.match(regex));
// Output: ["JavaScript", "JavaScript"]

In the code above:

  • Line 2: We use a regular expression /javascript/gi to find all (global, g) case-insensitive (i) occurrences of “javascript” within the string text.

  • Line 4: We call the match() method to return an array of the matches, which is then printed to the console.

Example 3: Replacing text dynamically with replace()#

The replace() method allows you to replace matched text with another string.

Javascript (babel-node)
const text = "I love JS!";
console.log(text.replace(/JS/, "JavaScript"));
// Output: "I love JavaScript!"

In the code above:

  • Line 1: We assign a string “I love JS!” to the constant variable text.

  • Line 3: We call the replace() method on the text string. The regular expression /JS/ defines the pattern to be replaced. The "JavaScript" is the replacement string. The first matched instance in the original string will be replaced with “JavaScript.”

You can even use capture groups ($1, $2, etc.) to dynamically replace text:

Javascript (babel-node)
const name = "Doe, John";
const formatted = name.replace(/(\w+), (\w+)/, "$2, $1");
console.log(formatted);
// Output: "John, Doe"

In the code above:

  • Line 1: We assign a string "Doe, John" to the constant variable name.

  • Line 2: The replace() method is called on the name string with the /(\w+), (\w+)/ regular expression, and "$2 $1" is the replacement string.

    • (\w+): This matches a word (letters, numbers, and underscore but not spaces). The parentheses create a capturing group. The first (\w+) captures the last name.

    • (\w+): This matches one word again, capturing the first name.

    • $2, $1: Here, $2 refers to the second captured group (the first name), whereas $1 refers to the first captured group (the second name). Hence, the replacement string $2, $1 re-constructs the formatted variable in the following order: the second captured group (first name), a comma, a space, and then the first captured group (last name).

  • Line 4: We print the reformatted name string to the console.

This method can format dates (YYYY-MM-DDDD/MM/YYYY), change username formats, etc.

Example 4: Extracting complex data with exec()#

Unlike match(), the exec() method returns detailed match information, including groups. It can extract parts of structured data like dates, emails, and phone numbers.

Javascript (babel-node)
const regex = /(\d{3})-(\d{2})-(\d{4})/;
const result = regex.exec("My SSN is 123-45-6789.");
console.log(result[0]); // Full match: "123-45-6789"
console.log(result[1]); // First group: "123"
console.log(result[2]); // Second group: "45"
console.log(result[3]); // Third group: "6789"

In the code above:

  • Line 1: We define the regular expression: /(\d{3})-(\d{2})-(\d{4})/

    • (\d{3}): Matches exactly three digits. The parentheses create a capturing group, meaning this part of the match will be accessible later.

    • -: Matches a hyphen.

    • (\d{2}): Matches exactly two digits (and is another capturing group).

    • -: Matches a hyphen.

    • (\d{4}): Matches exactly four digits (and is a third capturing group).

  • Line 3: We execute the regular expression against the string “My SSN is 123-45-6789.”. The exec() method returns an array-like object containing information about the match. If no match is found, it returns null.

  • Line 5: We print the entire matched string (“123-45-6789”) to the console.

  • Lines 6–8: We print all capturing groups to the console.

Example 5: Email validation#

Regex is widely used for form validation. Let’s see how to validate an email address:

Javascript (babel-node)
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test("user@example.com")); // true
console.log(emailRegex.test("invalid-email")); // false

In the code above:

  • Line 1: We define the regular expression for email validation: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/

    • ^: Matches the beginning of the string.

    • [a-zA-Z0-9._%+-]+: Matches one or more alphanumeric characters, periods, underscores percent signs, plus or minus signs. This part represents the username portion of the email address.

    • @: Matches the “@” symbol.

    • [a-zA-Z0-9.-]+: Matches one or more alphanumeric characters, periods, or hyphens. This is the domain name part.

    • \.: Matches a literal period (the \ escapes the special meaning of the dot in regex).

    • [a-zA-Z]{2,}: Matches two or more alphabetic characters. This is the top-level domain (like .com, .org, .net).

    • $: Matches the end of the string.

  • Line 3: We test the string “user@example.com” against the emailRegex and print it to the console.

  • Line 4: We test the string “invalid-email” against the emailRegex and print it to the console.

Example 6: Password validation#

A strong password consists of at least one lowercase letter, one uppercase letter, one digit, one special character, and a minimum length of 8.

Javascript (babel-node)
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
const passwords = ["P@$$wOrd", "weak", "12345678", "NoSpecialChars"];
passwords.forEach(password => {
console.log(`${password}: ${passwordRegex.test(password)}`);
});

In the code above:

  • Line 1: We define a regular expression for password validation: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/

    • ^ matches the beginning of the string.

    • (?=.*[a-z]) ensures that the password contains at least one lowercase letter. .* matches any character (except a newline) zero or more times, and [a-z] matches any lowercase letter.

    • (?=.*[A-Z]) ensures the password contains at least one uppercase letter.

    • (?=.*\d) ensures the password contains at least one digit (0-9).

    • (?=.*[@$!%*?&]) ensures the password contains at least one special character from the set @$!%*?&.

    • [A-Za-z\d@$!%*?&]{8,} matches eight or more characters from the allowed set (uppercase and lowercase letters, digits, and special characters).

    • $ matches the end of the string.

  • Line 3: We create an array of test passwords.

  • Lines 5–7: We iterate through each password in the passwords array. We use the test() method inside the loop to check if the current password matches the passwordRegex and log it to the console. Let’s examine the output:

    • P@$$wOrd: false: Fails because it lacks a digit. Replacing the O with 0 will make it a correct password.

    • weak: false: Fails because it’s too short and lacks uppercase, digits, and special characters.

    • 12345678: false: Fails because it lacks uppercase, lowercase, and special characters.

    • NoSpecialChars: false: Fails because it lacks digits and special characters.

Example 7: Extracting URLs#

Extracting specific information from text, such as URLs, is a common task. Regular expressions provide a powerful and concise way to achieve this. Here’s how you can extract URLs from a string using JavaScript:

Javascript (babel-node)
const text = "Visit our website: https://www.example.com and also check out http://blog.example.net";
const urlRegex = /(https?:\/\/[^\s]+)/g; // Capture group for the URL
const urls = text.match(urlRegex);
console.log(urls); // Output: ["https://www.example.com", "http://blog.example.net"]

In the code above:

  • Line 1: We define the string containing the URLs we want to extract.

  • Line 2: We define the regular expression for matching URLs: /(https?:\/\/[^\s]+)/g

    • https?: Matches “http” or “https”. The ? makes the “s” optional.

    • :\/\/: Matches “//”. The \ characters escape the forward slashes, which have special meaning in regex.

    • [^\s]+: Matches one or more characters that are not whitespace. This captures the rest of the URL.

    • (...): The parentheses create a capturing group to capture the matched URL.

    • g: This flag makes the regex “global,” meaning it will find all matches in the string, not just the first one.

  • Line 4: We use the match() method to find all matches of the urlRegex in the text string.

  • Line 5: We print the array of URLs to the console.

The g flag finds all URLs. The parentheses create a capture group, so match() returns the URLs.

Example 8: Phone number formatting#

Formatting phone numbers consistently can improve readability and user experience. Regular expressions provide a clean way to achieve this. Here’s a JavaScript function that formats a 10-digit phone number into the (XXX) XXX-XXXX format:

Javascript (babel-node)
const formatPhone = (phone) => {
return phone.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
};
console.log(formatPhone("1234567890")); // (123) 456-7890

In the code above:

  • Lines 1–3: We declare a constant function named formatPhone. We use an arrow function => which takes phone (a string of 10 digits) as input. Inside this function, we call the .replace() method on the phone string, using a regular expression pattern to find and format the number.

    • /: Denotes the start and end of the regex pattern.

    • (\d{3}): Matches exactly 3 digits (first group - area code).

    • (\d{3}): Matches next 3 digits (second group - prefix).

    • (\d{4}): Matches last 4 digits (third group - line number).

    • ($1): Wraps the first group (area code) in parentheses.

    • $2: Keeps the second group as-is.

    • -$3: Places a hyphen before the third group.

  • Line 5: We call the formatPhone() function with a sample 10-digit phone number and print the formatted number to the console.

Example 9: Extracting hashtag#

Hashtags are commonly used on social media to categorize content. We can use regular expressions to extract hashtags from a given text in JavaScript. This helps filter tweets and categorize content.

Javascript (babel-node)
const text = "Coding is #fun! #JavaScript";
const hashtags = text.match(/#\w+/g); // ["#fun", "#JavaScript"]
console.log(hashtags);

In the code above:

  • Line 1: We create a string text that contains hashtags: #fun and #JavaScript.

  • Line 3: We call the match() method to find all words starting with # using the regular expression: /#\w+/g

    • #: Matches the # symbol.

    • \w+: Matches one word of characters (A-Z, a-z, 0-9, _).

    • /g: a global flag ensures all matches in the string are found.

Regex best practices#

  • Keep it simple: Overly complex patterns become unreadable.

  • Comment your patterns: Use x flag (ES6+) for multiline regex:

const regex = /^\d+ # Match one or more digits
$/x;
  • Test rigorously: Use tools like RegExr to debug.

If you want to learn in detail about JavaScript Regular Expressions, do check out Educative’s course:

Cover
JavaScript Regular Expressions in Detail

Regular Expressions, also known as Regex, come in handy in a multitude of text processing scenarios. Regex defines a search pattern using symbols and allows you to find matches within strings. The applications of this span from software engineering to data science and beyond. In this course, you will begin with an introduction to regex, its history, and various types of regular expressions. You will then learn how to create your own regular expressions using various techniques and special characters. In the latter half of the course, you will explore RegExp Objects, how to parse data, turn phrases into an array of strings, and lastly password and email pattern matching. By the end of this course, you will be a regular expressions expert.

3hrs
Beginner
14 Playgrounds
3 Quizzes

Wrapping up and next steps#

JavaScript’s regex might look complex at first, but once you understand common patterns and how to use methods like test(), exec(), match(), replace(), and search(), it becomes an incredibly useful tool for working with text efficiently.

To expand your JavaScript expertise, explore these related blogs:

To deepen your knowledge, start your journey today with Educative’s JavaScript courses and transform your potential into expertise. Let’s build something incredible together.

Some of the latest courses available on our platform include:

Happy learning!


Frequently Asked Questions

How can regex be used to match time formats?

To use regex for matching time formats, define a pattern that fits the desired format. For example, ^([01]?[0-9]|2[0-3]):[0-5][0-9]$ matches 24-hour time, while ^(0?[1-9]|1[0-2]):[0-5][0-9]\s?(AM|PM)$ works for 12-hour time with AM/PM. Adjust patterns for variations like optional seconds or leading zeros. Regex ensures accurate time format validation.

What is regex expression in JavaScript?

A regular expression (regex) in JavaScript is a powerful tool for text processing. Here’s how it works:

  • It is a pattern used for matching and manipulating text.
  • Created using regex literals (/pattern/) or the RegExp() constructor.
  • Commonly used for input validation, searching, extracting, and replacing text.
  • Example: /\d+/g matches all numbers in a string.

How long does it take to learn regex?

Learning regex depends on your prior programming and pattern-matching experience. Here’s a general timeline:

  • Basic concepts (matching characters, quantifiers, common patterns) can be learned in a few hours.
  • Advanced features (lookaheads, lookbehinds, complex expressions) may take days to weeks of practice.
  • Hands-on experience in real-world scenarios speeds up learning significantly.

What are standard regex expressions?

Standard regex expressions are commonly used patterns designed for specific text-matching tasks. Some of the most widely used include:

  • Email validation: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  • Phone number validation: /^\d{10}$/ (matches a 10-digit number)
  • Only numbers: /^\d+$/ (matches whole numbers)
  • Only letters: /^[a-zA-Z]+$/
  • Alphanumeric characters: /^[a-zA-Z0-9]+$/
  • Whitespace removal: /\s+/g (matches all spaces)
  • Extract numbers from the text: /\d+/g

These expressions help with input validation, text extraction, and formatting, making them essential for various programming tasks.

Why is regex called a regular expression?

Regex is called ​​a “regular expression” because it is based on formal language theory and represents a regular language—a set of strings defined by specific rules. The term originated from automata theory and formal grammar, where “regular expressions” describe patterns that finite state machines could recognize. Over time, regular expressions became widely adopted in programming for pattern matching, text searching, and string manipulation, leading to the shortened term regex.

Can I use the replace() method to format dates?

Combined with regular expressions, the replace() method is a powerful tool for reformatting string dates. The replace() method allows you to find date patterns within a string and rearrange or modify the components (year, month, day) using regular expressions that capture groups and backreferences.

Let’s say you have a date in YYYY-MM-DD format and want to convert it to MM/DD/YYYY.

const date = "2023-10-27";
const formattedDate = date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
console.log(formattedDate); // Output: 10/27/2023

In the code above:

  • We define a regular expression /(\d{4})-(\d{2})-(\d{2})/. \d{4} matches four digits (year), \d{2} matches two digits (month or day).
  • The parentheses () create capturing groups, so the year, month, and day are captured.
  • The replace() method finds the matching pattern.
  • The second argument, "$2/$3/$1", is the replacement string.
  • $1, $2, and $3 are backreferences that refer to the captured groups (year, month, and day, respectively). They’re used to rearrange the date components.

Why doesn’t my regex work as expected?

Debugging regex can be tricky! Here’s what to check:

  • Are you using the correct flags? (g for global, i for case-insensitive, etc.)
  • Do you need to escape special characters? (. matches any character; use \. for a literal dot.)
  • Are quantifiers too greedy? Use *? or +? for non-greedy matches.
  • Have you tested with online tools? Try RegExr or regex101 to debug patterns visually.


Written By:
Amanda Fawcett

Free Resources