HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Regular Expressions

A regular expression (RegExp) is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text replace operations.


Syntax

In JavaScript, regular expressions are often used with / separators:

/pattern/modifiers;

// Example
let pattern = /redohub/i; 
  • redohub is a pattern (used in a search).
  • i is a modifier (modifies the search to be case-insensitive).

RegExp Modifiers

Modifiers can be used to perform case-insensitive and global searches:

  • i: Perform case-insensitive matching.
  • g: Perform a global match (find all matches rather than stopping after the first).
  • m: Perform multiline matching.

String Methods with RegExp

Regular expressions are frequently used with the search() and replace() string methods.

let text = "Visit RedoHub!";
let n = text.search(/redohub/i); // Returns 6 (the index)

let result = text.replace(/redohub/i, "Google"); // "Visit Google!"

The RegExp Object: test()

The test() method is a RegExp expression method. It searches a string for a pattern, and returns true or false, depending on the result.

const pattern = /e/;
pattern.test("The best things in life are free!"); // returns true
Common Use Case: Regular expressions are the primary tool for Form Validation (e.g., checking if an email or password follow specific security rules).

Key Points to Remember

  • RegExp allows for powerful text-based rules
  • The i modifier is essential for user input matching (ignore case)
  • replace() is much more powerful when used with global (g) regex
  • test() is the cleanest way to check for a simple match
  • Brackets [] define ranges (e.g., [0-9])
  • Metacharacters (like \d for digits) save time and typing