JS RegExp Methods

JavaScript RegExp Methods

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().


1. The test() Method

The 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.

RegExp test() Example

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 than match() or exec().


2. The exec() Method

The 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.

RegExp exec() Example

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);

Iterating with exec() and the g Flag

Because 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!

Looping with exec() Example

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}); }


Exercise

?

If you want a boolean (true or false) answer to whether a regular expression matches a string, which method should you use?