Clean β’ Professional
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.
test()true if the pattern matches, false otherwise.lastIndex if g or y 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)
exec()null if no match.[0])g or y 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
Regular expressions can be passed to string methods for advanced pattern matching.
a) match()
null.g flag: returns all matches.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()
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"]Β