Regular Expression Methods (RegExp Methods)
RegExp objects in JavaScript provide several methods to test, match, and manipulate strings using regular expressions. These methods can be directly used on the RegExp object or via string methods that accept a regex.
1. test()
- Checks if a pattern exists in a string.
- Returns
true
if the pattern matches,false
otherwise. - Updates
lastIndex
ifg
ory
flags are used.
Syntax:
regex.test(string)
Example:
const regex = /cat/;
console.log(regex.test("I have a cat")); // true
console.log(regex.test("I have a dog")); // false
With global flag:
const regex = /cat/g;
console.log(regex.test("cat cat")); // true
console.log(regex.lastIndex); // 3 (index after first match)
2. exec()
- Searches for a match and returns an array of details or
null
if no match. - The array includes:
- Matched text (
[0]
) - Captured groups (if any)
- Index of the match
- Input string
- Matched text (
- Works iteratively with
g
ory
flags.
Syntax:
regex.exec(string)
Example:
const regex = /cat/g;
const str = "cat bat 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
3. String Methods Using RegExp
Regular expressions can be passed to string methods for advanced pattern matching.
a) match()
- Returns an array of matches or
null
. - With
g
flag: returns all matches. - Without
g
flag: returns first match and captured groups.
const str = "cat bat rat";
console.log(str.match(/a.t/g)); // ["cat", "bat", "rat"]
console.log(str.match(/a.t/)); // ["cat", index: 1, input: "cat bat rat", groups: undefined]
b) matchAll()
(ES2020+)
Returns an iterator of all matches including captured groups.
const str = "cat bat rat";
const matches = str.matchAll(/(\\w)a(\\w)/g);
for (const m of matches) {
console.log(m);
}
// ["cat", "c", "t", index: 0, input: "cat bat rat", groups: undefined]
// ["bat", "b", "t", index: 4, ...]
// ["rat", "r", "t", index: 8, ...]
c) replace()
Replaces matched substrings with a replacement string or function.
const str = "cat bat rat";
console.log(str.replace(/a.t/g, "dog")); // "dog dog dog"
// Using captured groups
console.log(str.replace(/(\\w)a(\\w)/g, "$2$1")); // "tca tba tra"
d) search()
- Returns the index of the first match.
- Returns
1
if no match.
const str = "I have a cat";
console.log(str.search(/cat/)); // 9
console.log(str.search(/dog/)); // -1
e) split()
Splits a string using a regex as a separator.
const str = "apple,banana;cherry|date";
const result = str.split(/[,;|]/);
console.log(result); // ["apple", "banana", "cherry", "date"]