JAVASCRIPT

JavaScript Regex: Syntax, Usage, and Examples

JavaScript regex (short for regular expression) enables pattern-based text processing within strings. Developers use it to search, match, and manipulate text in concise and powerful ways. Regex integrates seamlessly with JavaScript’s string methods and helps handle tasks like input validation, data extraction, and format enforcement.

We explore how to write effective patterns, use them with different string methods, and troubleshoot issues with the help of a JavaScript regex tester.


What Is JavaScript Regex?

A regular expression is a sequence of characters that forms a search pattern. In JavaScript, regex appears either as a literal enclosed in slashes (e.g., /abc/) or as a RegExp object created using a constructor.

The JavaScript regex engine compares the pattern to parts of a string and returns matching content or a result based on evaluation.


Declaring Regex in JavaScript

You can create a regex in two ways:

1. Regex Literal

const regex = /hello/;

This form is concise and recommended for static patterns.

2. RegExp Constructor

const regex = new RegExp("hello");

This approach works well when you need to build patterns dynamically from variables.


Regex Flags in JavaScript

Regex flags change how the pattern behaves. Add them after the closing slash:

  • g: Global match (does not stop after the first match)
  • i: Case-insensitive match
  • m: Multiline mode (treats ^ and $ as the start/end of each line)
  • s: Allows . to match newline characters
  • u: Enables Unicode mode
  • y: Sticky mode (matches from the last index only)

const pattern = /hello/gi;

This pattern finds all instances of “hello” regardless of case.


Using JavaScript Regex with String Methods

Several string methods accept regular expressions, including match, test, replace, search, and split.

1. match()

This method returns an array of results or null if no match is found.

const result = "Color: #FF5733".match(/#[0-9A-F]{6}/i);
console.log(result[0]); // #FF5733

2. test()

This method checks if the pattern matches and returns a boolean.

const pattern = /\d+/;
console.log(pattern.test("abc123")); // true

Use this for validation checks or conditional logic.

3. replace()

Replace matched content with another string.

const result = "I have 2 cats".replace(/\d/, "three");
console.log(result); // I have three cats

It also accepts a function as the replacement argument for more advanced transformations.


Common Regex Symbols and Their Meanings

Understanding core regex syntax makes pattern writing easier:

  • .: Matches any character except a newline
  • \d: Matches a digit (0–9)
  • \D: Matches a non-digit
  • \w: Matches alphanumeric characters and underscores
  • \W: Matches non-word characters
  • \s: Matches any whitespace
  • \S: Matches non-whitespace
  • ^: Anchors to the beginning of the string
  • $: Anchors to the end of the string
  • [...]: Matches any one of the characters inside
  • [^...]: Matches any character not inside
  • : Matches 0 or more times
  • +: Matches 1 or more times
  • ?: Matches 0 or 1 time
  • {n}: Matches exactly n times
  • {n,}: Matches n or more times
  • {n,m}: Matches between n and m times

Practical Examples of Regex in JavaScript

Extracting Numbers

const text = "Item #4567";
const id = text.match(/\d+/)[0];
console.log(id); // 4567

This pattern captures numeric sequences using \d+.

Matching an Email Address

const emailRegex = /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test("user@example.com")); // true

Regex helps validate common formats with a single line of code.

Finding Repeated Characters

const repeated = "hellooo".match(/(.)\1+/g);
console.log(repeated); // ["ll", "ooo"]

Use backreferences like \1 to match repeated characters.


Using Regex Groups and Backreferences

Capturing groups use parentheses () to store matched segments.

const date = "2025-06-30";
const match = date.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(match[1]); // 2025

In replacements, backreferences are available using $1, $2, etc.

const reversed = date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1");
console.log(reversed); // 30/06/2025

Regex for JavaScript Input Validation

Input validation is one of the most common uses of JavaScript and regex.

Password Validation

const strongPass = /^(?=.*[A-Z])(?=.*\d).{8,}$/;
console.log(strongPass.test("Secure1")); // true

Phone Number Check

const phone = /^\d{3}-\d{3}-\d{4}$/;
console.log(phone.test("555-123-4567")); // true

These examples demonstrate how regex simplifies complex conditions.


Using a JavaScript Regex Tester

Online regex testers help developers build, test, and visualize expressions.

Popular tools include:

Paste a regex pattern and test strings to see matches and explanations. A JavaScript regex tester saves time and reduces trial-and-error debugging.


Performance Tips

Efficient regex patterns help prevent performance issues and bugs.

1. Avoid Greedy Wildcards

Use .*? instead of .* when you need minimal matches.

2. Cache Static Regex

Define regex patterns once, especially in loops or repeated function calls.

3. Watch for Catastrophic Backtracking

Avoid nested quantifiers like /((a+)+)/, which can freeze the browser for long strings.


Regex in JavaScript for Dynamic Searches

You can generate patterns dynamically using the RegExp constructor.

const word = "alert";
const pattern = new RegExp(word, "gi");
console.log("ALERT!".match(pattern)); // ALERT

Dynamic construction makes it easy to integrate user inputs or variable data into regex.


Regex in Combination with Arrays

Split strings using regex or search arrays of text.

const result = "apple, banana; cherry".split(/[,;]/);
console.log(result); // ["apple", " banana", " cherry"]

This approach allows flexible handling of multiple delimiters.


Combining Regex with Other JavaScript Techniques

Regex pairs well with functions like filter() or map():

const emails = ["admin@example.com", "info@test.org", "hello@example.com"];
const filtered = emails.filter(email => /@example\.com$/.test(email));
console.log(filtered); // ["admin@example.com", "hello@example.com"]

You can extract or validate data at scale with minimal code.


Summary

JavaScript regex provides a compact and expressive way to handle pattern matching, text manipulation, and input validation. You can use it to extract numbers, validate emails, format strings, and more. Built-in methods like match, test, and replace give developers complete control over how regex patterns interact with strings.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster