Clean β’ Professional
In JavaScript, a RegExp object is used to create and work with regular expressionsβpatterns for matching, searching, and manipulating strings. RegExp objects provide methods, properties, and flags to control pattern matching behavior.
There are two ways to create a RegExp object:
a) Using a Literal (Recommended for Static Patterns)
const regex = /hello/i; // i β case-insensitive
console.log(regex.test("HELLO")); // true
b) Using the RegExp Constructor (Dynamic Patterns)
Useful when the pattern is stored in a variable or generated dynamically.
const pattern = "hello";
const regex = new RegExp(pattern, "i"); // i β case-insensitive
console.log(regex.test("HELLO")); // true
Flags modify the behavior of the regex and are added after the pattern or as the second argument in the constructor:
Example:
const regex = /cat/gi;
console.log("Cat cat CAT".match(regex)); // ["Cat", "cat", "CAT"]
| Property | Description |
|---|---|
source | Returns the pattern as a string. |
flags | Returns the flags used. |
lastIndex | Index where the next match starts (used with g or y). |
global | true if g flag is set. |
ignoreCase | true if i flag is set. |
multiline | true if m flag is set. |
sticky | true if y flag is set. |
unicode | true if u flag is set. |
dotAll | true if s flag is set. |
Example:
const regex = /hello/gi;
console.log(regex.source); // "hello"
console.log(regex.flags); // "gi"
console.log(regex.global); // true
console.log(regex.ignoreCase); // true
a) test(string)
Checks if the pattern exists in a string; returns true or false.
const regex = /cat/;
console.log(regex.test("I have a cat")); // true
console.log(regex.test("I have a dog")); // false
b) exec(string)
Searches for a match and returns an array with details, or null if no match.
g flag for iterative matching.const regex = /cat/g;
const str = "cat hat cat";
let match;
while ((match = regex.exec(str)) !== null) {
console.log(`Found "${match[0]}" at index ${match.index}`);
}
// Found "cat" at index 0
// Found "cat" at index 8
RegExp patterns can be applied with string methods:
| Method | Description |
|---|---|
match() | Returns array of matches or null. |
matchAll() | Returns iterator with all matches and groups (ES2020+). |
replace() | Replaces matches with string or function. |
search() | Returns index of first match or -1. |
split() | Splits string by regex pattern. |
Example:
const str = "cat bat rat";
console.log(str.match(/a.t/g)); // ["cat", "bat", "rat"]
console.log(str.replace(/a.t/g, "dog")); // "dog dog dog"
console.log(str.split(/ /)); // ["cat", "bat", "rat"]
console.log(str.search(/bat/)); // 4
g or y flags, lastIndex tracks where the next match starts.exec() and test() update lastIndex automatically.const regex = /cat/g;
const str = "cat bat cat";
console.log(regex.lastIndex); // 0
regex.exec(str); // ["cat", index: 0]
console.log(regex.lastIndex); // 3 (after first match)
regex.exec(str); // ["cat", index: 8]
console.log(regex.lastIndex); // 11Β