Difference between test () and exec () methods in Javascript

JavascriptFront End TechnologyObject Oriented Programming

Test tests for matches and returns booleans while exec captures groups and matches the regex to the input.

If you only need to test an input string to match a regular expression, RegExp.test is most appropriate. It will give you a boolean return value which makes it ideal for conditions.

RegExp.exec gives you an array-like return value with all capture groups and matched indexes. Therefore, it is useful when you need to work with the captured groups or indexes after the match.

Example

console.log(/^([a-z]+) ([A-Z]+)$/.exec("hello WORLD"))
console.log(/^([a-z]+) ([A-Z]+)$/.test("hello WORLD"))

Output

[ 'hello WORLD', 
   'hello', 
   'WORLD', 
   index: 0, 
   input: 'hello WORLD', 
   groups: undefined ] 
true

Note that the first index in the array returned by exec is the complete matched string. The following indices are the individual groups captured by the regex.

raja
Published on 16-Sep-2019 11:40:55
Advertisements