Course

JavaScript Regular Expressions: Syntax, Usage, and Examples

JavaScript regular expressions (regex) help you search, match, and manipulate text using patterns. You can use them to validate user input, extract data, or modify text dynamically.

How to Use JavaScript Regular Expressions

You create a regular expression in JavaScript using either the literal syntax or the RegExp constructor.

Regular Expression Syntax

jsx
// Regular expression literal let regex = /hello/; // RegExp constructor let regex2 = new RegExp("hello");
  • Slashes (/ /) define a regex literal.
  • The RegExp constructor creates a dynamic pattern.

You can test a pattern against a string using .test() or .exec().

jsx
let pattern = /JavaScript/; console.log(pattern.test("I love JavaScript")); // true console.log(pattern.test("Python is great")); // false

When to Use JavaScript Regular Expressions

  1. Form validation – Validate email addresses, phone numbers, or passwords.
  2. Text search and replacement – Find specific words and modify them.
  3. Data extraction – Extract dates, numbers, or patterns from text.

Examples of JavaScript Regular Expressions

Validating an Email

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

Replacing Words in a String

jsx
let text = "I love JavaScript!"; let updatedText = text.replace(/JavaScript/, "Python"); console.log(updatedText); // "I love Python!"

Extracting Numbers

jsx
let sentence = "The price is $45.99"; let price = sentence.match(/\d+\.\d+/); console.log(price[0]); // "45.99"

Learn More About JavaScript Regular Expressions

Understanding Regular Expressions in JavaScript

Regular expressions use special characters to define patterns.

jsx
let regex = /\d{3}-\d{2}-\d{4}/; // Matches a format like 123-45-6789 console.log(regex.test("123-45-6789")); // true console.log(regex.test("12-3456-789")); // false
  • \d matches any digit (0-9).
  • {3} means exactly three occurrences.
  • `` is a literal hyphen.

Flags in Regular Expressions

Flags modify how a regex works.

jsx
let sentence = "Hello hello"; let caseInsensitivePattern = /hello/i; // Case insensitive flag (i) console.log(caseInsensitivePattern.test(sentence)); // true let globalPattern = /l/g; // Global search flag (g) console.log(sentence.match(globalPattern)); // ['l', 'l', 'l', 'l']

How to Combine Two Regular Expressions in JavaScript

You can combine patterns using the pipe | (OR operator).

jsx
let fruitPattern = /apple|banana/; console.log(fruitPattern.test("I like bananas")); // true console.log(fruitPattern.test("I like grapes")); // false

Advanced Regular Expressions in JavaScript

You can use lookaheads, lookbehinds, and capturing groups for advanced pattern matching.

Positive Lookahead

Matches only if another pattern follows.

jsx
let lookaheadPattern = /\d+(?= dollars)/; console.log("20 dollars".match(lookaheadPattern)); // ["20"] console.log("20 euros".match(lookaheadPattern)); // null

Negative Lookahead

Matches only if another pattern does not follow.

jsx
let negativeLookahead = /\d+(?! euros)/; console.log("30 dollars".match(negativeLookahead)); // ["30"] console.log("30 euros".match(negativeLookahead)); // null

Capturing Groups

Extracts parts of a match.

jsx
let datePattern = /(\d{4})-(\d{2})-(\d{2})/; let result = "2024-02-01".match(datePattern); console.log(result[1]); // "2024" console.log(result[2]); // "02" console.log(result[3]); // "01"

Testing Regular Expressions in JavaScript

You can use .test(), .match(), or .exec().

jsx
let pattern = /hello/; console.log(pattern.test("hello world")); // true let matchResult = "hello world".match(/hello/); console.log(matchResult[0]); // "hello" let execResult = /(\d+)/.exec("Price: 99"); console.log(execResult[1]); // "99"

Common Mistakes with Regular Expressions

  1. Forgetting escape characters – Special characters like . and `` need escaping.
  2. Not using global (g) when needed – Without it, match() returns only the first match.
  3. Overusing regex for simple tasks – Sometimes split(), includes(), or replace() is enough.

Regular expressions in JavaScript are a powerful tool for searching, replacing, and validating text. Mastering them helps with data processing, input validation, and text parsing.