Patterns and Flags in JavaScript

Patterns and Flags in JavaScript

Patterns and Flags in JavaScript

In JavaScript, patterns and flags are commonly associated with regular expressions (regex). A regular expression is a sequence of characters that forms a search pattern. It can be used for string searching, matching, replacing, or splitting text. Flags in regular expressions alter the behavior of pattern matching.

Regular Expressions Overview

A regular expression is created using the following syntax:

let pattern = /expression/flags;
  • expression: Defines the pattern you want to match.
  • flags: Optional modifiers that change how the expression behaves.

Regular Expression Syntax

  • .: Matches any single character except newline.
  • ^: Anchors the match to the beginning of the string.
  • $: Anchors the match to the end of the string.
  • []: Matches any one of the enclosed characters.
  • [^]: Matches any character except those in the brackets.
  • |: OR operator, matches either the pattern before or after it.
  • (): Groups patterns together.
  • {}: Specifies the number of occurrences.
  • +: Matches one or more of the preceding token.
  • *: Matches zero or more of the preceding token.
  • ?: Matches zero or one of the preceding token.

Flags

Flags modify how the regular expression engine processes the pattern. Here are the most commonly used flags:

  1. g (global search):

    • This flag searches the entire string rather than stopping after the first match.
    • Example:
      let pattern = /abc/g; let str = 'abc abc abc'; console.log(str.match(pattern)); // ["abc", "abc", "abc"]
  2. i (ignore case):

    • This flag makes the pattern case-insensitive.
    • Example:
      let pattern = /hello/i; let str = 'Hello World'; console.log(str.match(pattern)); // ["Hello"]
  3. m (multiline mode):

    • This flag changes the behavior of ^ and $ to match the start and end of a line, not just the start and end of the string.
    • Example:
      let pattern = /^hello/m; let str = `hello world hello`; console.log(str.match(pattern)); // ["hello", "hello"]
  4. s (dotall mode):

    • This flag allows . to match newline characters as well.
    • Example:
      let pattern = /hello.world/s; let str = `hello world`; console.log(pattern.test(str)); // true
  5. u (unicode):

    • This flag enables full Unicode matching, which is useful when dealing with Unicode characters beyond the basic ASCII range.
    • Example:
      let pattern = /\u{1F600}/u; // Matches the 😀 character (Unicode emoji) let str = '😀'; console.log(pattern.test(str)); // true
  6. y (sticky):

    • This flag matches the pattern starting exactly at the current position of the string, making it more precise when searching within the string.
    • Example:
      let pattern = /abc/y; let str = 'abc abc abc'; console.log(pattern.exec(str)); // ["abc"] console.log(pattern.exec(str)); // null, because the search starts at the last match

Examples of Using Regular Expressions with Flags

  1. Matching Email Addresses (with g and i flags)

    Here’s an example where we use a regular expression to match email addresses in a string:

    let pattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b/g; let str = 'Contact us at example@domain.com or support@company.com'; let emails = str.match(pattern); console.log(emails); // ["example@domain.com", "support@company.com"]
    • g: Global flag to find all occurrences of email addresses.
    • i: Case-insensitive matching for the domain and username part.
  2. Validating a Phone Number (with i flag)

    Here's how you can validate a simple phone number format using a regex:

    let pattern = /\(\d{3}\) \d{3}-\d{4}/i; let str = '(123) 456-7890'; console.log(pattern.test(str)); // true
    • i: The flag makes the pattern case-insensitive, which is useful in scenarios where case might differ.
  3. Extracting Date from String (with g flag)

    If you have a string containing multiple dates, you can use a global regular expression to extract them:

    let pattern = /\d{2}\/\d{2}\/\d{4}/g; let str = 'The event is on 12/12/2025 and another one on 01/15/2026.'; let dates = str.match(pattern); console.log(dates); // ["12/12/2025", "01/15/2026"]
    • g: Global flag to find all the dates in the string.
  4. Extracting a Word Starting with "a" (with i and g flags)

    This example demonstrates how to match all words that start with "a", using global and case-insensitive flags.

    let pattern = /\ba\w*/gi; let str = 'Apples are amazing and awesome'; let words = str.match(pattern); console.log(words); // ["Apples", "are", "amazing", "awesome"]
    • g: Finds all matches.
    • i: Makes the pattern case-insensitive.

Flags in Action: Modifying the Behavior of Regex

Here’s a breakdown of how flags can change the behavior of a regular expression:

  • Without flags:

    let pattern = /abc/; let str = 'abc abc abc'; console.log(str.match(pattern)); // ["abc"]
  • With the g flag (global search):

    let pattern = /abc/g; let str = 'abc abc abc'; console.log(str.match(pattern)); // ["abc", "abc", "abc"]
  • With the i flag (case-insensitive):

    let pattern = /abc/i; let str = 'ABC abc aBc'; console.log(str.match(pattern)); // ["ABC"]
  • With the m flag (multiline):

    let pattern = /^abc/m; let str = `abc def abc`; console.log(str.match(pattern)); // ["abc", "abc"]

Conclusion

Regular expressions in JavaScript are a powerful tool for string pattern matching and manipulation. Flags are an essential part of regular expressions because they allow you to modify how the pattern matching behaves, making your regex more versatile and powerful. Flags like g, i, m, s, u, and y are commonly used to achieve different matching behaviors in various use cases.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close