Skip to Content
Course content

150: Regex Syntax in JavaScript

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Should I use the /slash/ notation or the RegExp constructor?

You'll see two ways to create a regular expression in JavaScript. The first is the literal notation: const regex = /abc/;. The second is the constructor: const regex = new RegExp('abc');.

In 95% of your work, just use the literal notation. It's cleaner, it's faster because it's compiled when the script is loaded, and you don't have to deal with "double-escaping" backslashes. I only reach for the new RegExp() constructor when the pattern needs to be dynamic—for example, if you're building a search feature where the user types the keyword into an input field and you need to turn that string into a regex on the fly.

// Static pattern: Use the literal
const zipCodeRegex = /^\d{5}$/; 

// Dynamic pattern: Use the constructor
const searchTerm = "javascript"; 
const dynamicRegex = new RegExp(searchTerm, 'gi');

What's the deal with all these backslashes and symbols?

Regex looks like a cat walked across your keyboard, but it's actually a very logical shorthand. When you see a backslash, think of it as a "special character" trigger. For instance, \d is shorthand for "any digit," and \s is "any whitespace."

Then you have the quantifiers. These tell JS how many of the previous character to look for. + means "one or more," * means "zero or more," and {3} means "exactly three." I find it helpful to read them aloud as phrases. So, if I'm looking for a product SKU that starts with two letters followed by four numbers, I'd write /[a-zA-Z]{2}\d{4}/. I read that as: "Two letters, then four digits."

const sku = "AB1234";
const skuPattern = /[a-zA-Z]{2}\d{4}/;

console.log(skuPattern.test(sku)); // true

What do the letters at the end of the regex actually do?

Those are flags. They modify how the entire search is performed. The two you'll use constantly are g (global) and i (case-insensitive).

By default, a regex stops after the first match. If you're trying to find every single instance of a word in a long paragraph, you must add the g flag. If you don't care if the user typed "JavaScript", "JAVASCRIPT", or "javascript", add the i flag. You can combine them, too, like /pattern/gi.

const text = "JavaScript is great. I love JAVASCRIPT!";
const regex = /javascript/gi;

// Without 'g', this would only return the first match
const matches = text.match(regex); 
console.log(matches); // ["JavaScript", "JAVASCRIPT"]

How do I pull out a specific piece of the match?

This is where "capturing groups" come in. By wrapping a part of your regex in parentheses (), you're telling JavaScript: "I need to match the whole thing, but I specifically want to remember this piece."

I use this all the time for parsing data. Let's say you have a string representing a price and a currency, like "USD 49.99", and you only want the numerical amount. You can group the digits and the decimal point to isolate them from the currency code.

const priceString = "USD 49.99";
const priceRegex = /([A-Z]{3})\s(\d+\.\d{2})/;
const match = priceString.match(priceRegex);

// match[0] is the full string
// match[1] is the first group (Currency)
// match[2] is the second group (Amount)
console.log(`Currency: ${match[1]}, Amount: ${match[2]}`); 
// Output: Currency: USD, Amount: 49.99



📋 Practical Task

Building a Logistics Order ID Validator

In a warehouse system, Order IDs must follow a very strict format: they start with the prefix "ORD-", followed by exactly 5 uppercase letters, another dash, and exactly 4 digits (e.g., ORD-XKJWP-1024).

Your task is to create a regular expression that validates this specific format. Then, write a small function that takes a string and returns true if it's a valid Order ID and false otherwise.

Requirements:

  • The pattern must be case-sensitive (uppercase only).
  • It must match the entire string from start to finish (use anchors ^ and $).
  • Test it against these cases: "ORD-XKJWP-1024" (valid), "ord-XKJWP-1024" (invalid), "ORD-XKJWP-123" (invalid), "ORD-XKJWP-10245" (invalid).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.