JavaScript Regular Expressions

Regular expressions (regex) in JavaScript are patterns used to match character combinations in strings. They are powerful tools for searching, matching, and replacing text.

 

Creating Regular Expressions

There are two ways to create a regular expression in JavaScript:

  1. Using Literal Syntax:
    let regex = /pattern/;
    

    Try It Now

  2. Using Constructor:
    let regex = new RegExp("pattern");
    

    Try It Now

Basic Syntax

  • /pattern/flags: The pattern is the text to search for, and the flags modify the search.

Common Flags:

  • g: Global search (find all matches).
  • i: Case-insensitive search.
  • m: Multi-line search.

Example:

let regex = /hello/i;  // Case-insensitive match for "hello"

Try It Now

Common Regex Patterns

  1. Literal Characters: Match exact characters.
    • /cat/ matches “cat”.
  2. Meta Characters: Special characters with specific meanings.
    • .: Matches any single character except newline.
    • ^: Matches the beginning of a string.
    • $: Matches the end of a string.
    • *: Matches 0 or more of the preceding element.
    • +: Matches 1 or more of the preceding element.
    • ?: Matches 0 or 1 of the preceding element.

Example:

let regex = /ca./;  // Matches "cat", "car", "can", etc.

Try It Now

Character Classes

  • [abc]: Matches any of the characters in the brackets.
  • [^abc]: Matches any character not in the brackets.
  • [0-9]: Matches any digit.
  • [a-z]: Matches any lowercase letter.
  • [A-Z]: Matches any uppercase letter.

Example:

let regex = /[0-9]/;  // Matches any digit

Try It Now

Predefined Character Classes

  • \d: Matches any digit (equivalent to [0-9]).
  • \D: Matches any non-digit character.
  • \w: Matches any alphanumeric character (equivalent to [A-Za-z0-9_]).
  • \W: Matches any non-word character.
  • \s: Matches any whitespace character.
  • \S: Matches any non-whitespace character.

Example:

let regex = /\d/;  // Matches any digit

Try It Now

Quantifiers

Quantifiers specify how many times a character or group should be matched.

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

Example:

let regex = /a{2,4}/;  // Matches "aa", "aaa", or "aaaa"

Try It Now

Regex Methods

    1. test(): Tests for a match in a string. Returns true or false.
      let regex = /cat/;
      console.log(regex.test("The cat is here."));  // true
      

      Try It Now

    2. exec(): Executes a search for a match in a string. Returns an array of matched results or null.
let regex = /cat/;
console.log(regex.exec("The cat is here."));  // ["cat"]

Try It Now

  1. String Methods with Regex:
    • match(): Returns an array of matches or null.
    • replace(): Replaces matched substring with a new substring.
    • search(): Searches for a match and returns the index or -1.
    • split(): Splits a string into an array using the regex.

Example:

let str = "The cat is here.";
let regex = /cat/;
console.log(str.match(regex));  // ["cat"]

Try It Now

Conclusion

Regular expressions are a powerful tool in JavaScript for text processing tasks like validation, searching, and replacing. By mastering regex patterns and methods., you can handle complex string operations efficiently.