Skip to content

RegExp in Javascript

Regular expressions (regex or regexp) are powerful tools for pattern matching and text manipulation. In JavaScript, regular expressions are implemented through the RegExp object and integrated into string methods. Here’s a detailed explanation of how regular expressions work in JavaScript:

Creating a Regular Expression

Regular expressions can be created in two ways:

  1. Using a Regular Expression Literal:

let regex = /pattern/flags;

  1. Using the RegExp Constructor:

let regex = new RegExp(‘pattern’, ‘flags’);

Flags

Flags are optional parameters that modify the behavior of the regular expression. The most common flags are:

  • g (global): Matches all occurrences in the string.
  • i (ignore case): Makes the regex case-insensitive.
  • m (multiline): Treats the start ^ and end $ characters as working across multiple lines.
  • s (dotAll): Allows the dot . to match newline characters.
  • u (unicode): Enables full Unicode support.
  • y (sticky): Matches from the last index position in the target string.

Basic Syntax

Here are some common components of regular expressions:

  • Literal Characters: Matches the exact characters.

let regex = /abc/; // Matches “abc”

  • Metacharacters: Characters with special meaning.

let regex = /a.b/; // Matches “a”, any character, and “b” (e.g., “a_b”, “a1b”)

  • Character Classes:
    • [abc]: Matches any one of the characters inside the brackets.
    • [^abc]: Matches any character not in the brackets.
    • [0-9]: Matches any digit.
    • [a-z]: Matches any lowercase letter.
    • \d: Matches any digit (equivalent to [0-9]).
    • \D: Matches any non-digit.
    • \w: Matches any word character (alphanumeric and underscore).
    • \W: Matches any non-word character.
    • \s: Matches any whitespace 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 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.
  • Groups and Ranges:
    • (abc): Matches the exact sequence “abc”.
    • (a|b): Matches either “a” or “b”.

Using Regular Expressions in JavaScript

1. Testing for Matches

  • test() Method: Tests for a match in a string. Returns true or false.

let regex = /hello/;

 let result = regex.test(‘hello world’); // true

2. Extracting Matches

  • exec() Method: Executes a search for a match in a string. Returns an array of matched results or null.

let regex = /hello/;

let result = regex.exec(‘hello world’);

console.log(result); // [“hello”]

  • match() Method: Retrieves the result of matching a string against a regular expression.

let str = ‘hello world’;

let regex = /hello/;

let result = str.match(regex);

console.log(result); // [“hello”]

3. Replacing Substrings

  • replace() Method: Replaces matched substrings with a new substring.

let str = ‘hello world’;

 let result = str.replace(/world/, ‘JavaScript’);

 console.log(result); // “hello JavaScript”

4. Searching for a Match

  • search() Method: Searches for a match and returns the index of the first match or -1.

let str = ‘hello world’;

 let result = str.search(/world/);

console.log(result); // 6

5. Splitting a String

  • split() Method: Splits a string into an array of substrings based on a pattern.

let str = ‘hello world’;

let result = str.split(/\s/);

 console.log(result); // [“hello”, “world”]

Examples of Regular Expressions

Matching Email Addresses

let regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

let email = ‘example@test.com’;

 console.log(regex.test(email)); // true

Matching Phone Numbers

let regex = /^\d{3}-\d{3}-\d{4}$/;

 let phone = ‘123-456-7890’;

console.log(regex.test(phone)); // true

Matching Dates (MM/DD/YYYY)

let regex = /^(0[1-9]|1[0-2])\/(0[1-9]|[12][0-9]|3[01])\/\d{4}$/;

 let date = ’12/25/2020′;

console.log(regex.test(date)); // true

Summary

Regular expressions in JavaScript are a versatile and powerful tool for pattern matching and text manipulation. Understanding the syntax and usage of regex allows for efficient handling of strings, making it easier to validate, search, and manipulate text.