JavaScript Interview Question #187
What is the difference between test(), match(), and exec() for regular expressions?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
RegExp.test returns a Boolean indicating whether a pattern matches. String.match returns match information, with behavior affected by flags such as g. RegExp.exec returns detailed information for the next match and can be used repeatedly with stateful global or sticky regular expressions.
Detailed Explanation
RegExp.test returns a Boolean indicating whether a pattern matches. String.match returns match information, with behavior affected by flags such as g. RegExp.exec returns detailed information for the next match and can be used repeatedly with stateful global or sticky regular expressions.
Choose the method based on whether you need only a yes/no result, collected matches, or detailed iterative matching information.
Code Example
const pattern = /\d+/g;
const text = "IDs: 10 and 20";
console.log(/\d+/.test(text)); // true
console.log(text.match(pattern)); // ["10", "20"]
const regex = /\d+/g;
console.log(regex.exec(text)?.[0]); // 10
console.log(regex.exec(text)?.[0]); // 20