In earlier chapters, we saw how to use String methods (like search() and replace()) with regular expressions. However, the RegExp object itself comes with two extremely powerful built-in methods: test() and exec().
test() MethodThe test() method is the simplest and fastest way to check if a pattern exists in a string.
It searches a string for a pattern, and returns true if it finds a match, or false if it doesn't.
let pattern = /e/;console.log(pattern.test("The best things in life are free!")); // true console.log(pattern.test("No way!")); // false
Best Practice: If you only need to know whether a string matches a pattern (yes or no), use
test(). It is faster thanmatch()orexec().
exec() MethodThe exec() method is more complex. It searches a string for a specified pattern and returns an Array containing information about the match (including the matched text, captured groups, and index).
If no match is found, it returns null.
let pattern = /e/;
let result = pattern.exec("The best things in life are free!");
console.log("Found: " + result[0]);
console.log("At index: " + result.index);
exec() and the g FlagBecause the RegExp object remembers the lastIndex property when using the global g flag, you can place exec() inside a while loop to find every single match and its exact position within a string!
let text = "cat bat rat"; let pattern = /at/g; let match;// Keep executing as long as match is not null while ((match = pattern.exec(text)) !== null) { console.log(
Found ${match[0]} at index ${match.index}); }
If you want a boolean (true or false) answer to whether a regular expression matches a string, which method should you use?