Day 19: Regular Expressions in JavaScript

Day 19: Regular Expressions in JavaScript

Welcome back to our JavaScript series! Today, we’ll explore Regular Expressions (RegEx) in JavaScript. Regular Expressions are powerful tools for matching patterns in text. They are used for searching, replacing, and extracting information from strings. We’ll cover the basics of RegEx, how to create and use them, and some common patterns.

What is a Regular Expression?

A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. You can use RegEx to perform complex string manipulation tasks like validation, searching, and replacing text.

Creating a Regular Expression

In JavaScript, you can create a Regular Expression in two ways:

  1. Literal Notation:

      const regex = /pattern/flags;
    
  2. RegExp Constructor:

      const regex = new RegExp('pattern', 'flags');
    

Basic Syntax

  • Characters:

    • .: Matches any character except newline.

    • \d: Matches any digit (0-9).

    • \w: Matches any word character (alphanumeric or underscore).

    • \s: Matches any whitespace character (space, tab, newline).

    • \D: Matches any non-digit character.

    • \W: Matches any non-word character.

    • \S: Matches any non-whitespace character.

  • Anchors:

    • ^: Matches the beginning of a string.

    • $: Matches the end of a string.

  • Quantifiers:

    • *: Matches 0 or more occurrences.

    • +: Matches 1 or more occurrences.

    • ?: Matches 0 or 1 occurrence.

    • {n}: Matches exactly n occurrences.

    • {n,}: Matches n or more occurrences.

    • {n,m}: Matches between n and m occurrences.

  • Character Classes:

    • [abc]: Matches any one of the characters a, b, or c.

    • [^abc]: Matches any character not a, b, or c.

    • [a-z]: Matches any character from a to z.

    • [0-9]: Matches any digit from 0 to 9.

  • Groups and Alternation:

    • (abc): Matches the exact sequence abc.

    • a|b: Matches either a or b.

Flags

  • g: Global search.

  • i: Case-insensitive search.

  • m: Multi-line search.

  • u: Unicode.

  • y: Sticky search.

Common Methods

test

The test method checks if a pattern exists in a string and returns true or false.

Example:

const regex = /hello/i;
const result = regex.test('Hello, world!');
console.log(result); // true

exec

The exec method searches for a match in a string and returns an array of results or null.

Example:

const regex = /hello/i;
const result = regex.exec('Hello, world!');
console.log(result); // [ 'Hello', index: 0, input: 'Hello, world!', groups: undefined ]

match

The match method retrieves the matches when matching a string against a regular expression.

Example:

const regex = /hello/i;
const result = 'Hello, world!'.match(regex);
console.log(result); // [ 'Hello', index: 0, input: 'Hello, world!', groups: undefined ]

The search method searches for a match between a regular expression and a string and returns the index of the match or -1.

Example:

const regex = /hello/i;
const result = 'Hello, world!'.search(regex);
console.log(result); // 0

replace

The replace method replaces matched substrings with a new substring.

Example:

const regex = /hello/i;
const result = 'Hello, world!'.replace(regex, 'Hi');
console.log(result); // Hi, world!

split

The split method splits a string into an array of substrings using a regular expression.

Example:

const regex = /,\s*/;
const result = 'apple, banana, cherry'.split(regex);
console.log(result); // [ 'apple', 'banana', 'cherry' ]

Common Patterns

Email Validation

Example:

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test('example@example.com')); // true

URL Validation

Example:

const urlRegex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w .-]*)*\/?$/;
console.log(urlRegex.test('https://www.example.com')); // true

Phone Number Validation

Example:

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

Password Strength Validation

Example:

const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
console.log(passwordRegex.test('Password1')); // true

Summary

Today, we explored Regular Expressions in JavaScript. We covered the basic syntax, how to create and use RegEx, common methods, and some useful patterns for validation. RegEx is a powerful tool for string manipulation and can significantly enhance your ability to process and validate text. In the coming days, we’ll continue to delve deeper into some more advanced topics. So stay tuned!