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.
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).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.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 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
i modifier is essential for user input matching (ignore case)replace() is much more powerful when used with global (g) regextest() is the cleanest way to check for a simple match[] define ranges (e.g., [0-9])\d for digits) save time and typing