🔍

How to Use Regular Expressions in JavaScript

JavaScriptIntermediate

Pattern matching with regular expressions.

Code Example

JavaScript
// Creating regex
const regex1 = /hello/;
const regex2 = new RegExp("hello", "i");

// Test method
console.log(/hello/.test("hello world")); // true
console.log(/hello/.test("goodbye")); // false

// Match method
const str = "The rain in Spain";
const match = str.match(/ain/g);
console.log(match); // ["ain", "ain"]

// Replace method
const text = "Hello World";
const replaced = text.replace(/World/, "JavaScript");
console.log(replaced); // "Hello JavaScript"

// Common patterns
const email = "user@example.com";
const emailRegex = /^[\w.-]+@[\w.-]+\.\w+$/;
console.log(emailRegex.test(email)); // true

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

// Character classes
console.log(/\d/.test("123")); // digit
console.log(/\w/.test("abc")); // word character
console.log(/\s/.test(" ")); // whitespace

// Quantifiers
console.log(/a+/.test("aaa")); // one or more
console.log(/a*/.test("")); // zero or more
console.log(/a?/.test("")); // zero or one
console.log(/a{3}/.test("aaa")); // exactly 3
console.log(/a{2,4}/.test("aaa")); // between 2 and 4

// Groups and capture
const date = "2024-01-15";
const dateMatch = date.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(dateMatch[1]); // "2024"
console.log(dateMatch[2]); // "01"
console.log(dateMatch[3]); // "15"

// Named groups
const namedMatch = date.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(namedMatch.groups.year); // "2024"

// Flags
console.log(/hello/gi.test("HELLO hello")); // global, case-insensitive

// Practical examples
// Validate URL
const url = "https://example.com";
const urlRegex = /^https?:\/\/[\w.-]+(?:\.[\w]+)+[\/\w.-]*$/;
console.log(urlRegex.test(url));

// Extract numbers
const text2 = "Order 123 items, total $456";
const numbers = text2.match(/\d+/g);
console.log(numbers); // ["123", "456"]

// Remove whitespace
const messy = "  hello   world  ";
const clean = messy.replace(/\s+/g, " ").trim();
console.log(clean); // "hello world"

Explanation

Regex patterns: \d digits, \w word chars, \s whitespace. Quantifiers: + (1+), * (0+), ? (0-1), {n,m}. Use test(), match(), replace(). Flags: g global, i case-insensitive.

Related Tutorials