regex test vs match

Solutions on MaxInterview for regex test vs match by the best coders in the world

showing results for - "regex test vs match"
Louka
21 Sep 2018
1// Syntax
2  
3  'string'.match(/regex/);
4  /regex/.test('string');
5
6// Explanation 1
7
8  match() method to extract the string.
9  test() to return boolean.
10
11  // Source: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/extract-matches
12
13// Explanation 2
14
15  // Don't forget to take into consideration the global flag in your regexp :
16
17  var reg = /abc/g;
18  !!'abcdefghi'.match(reg); // => true
19  !!'abcdefghi'.match(reg); // => true
20  reg.test('abcdefghi');    // => true
21  reg.test('abcdefghi');    // => false <=
22
23
24  // => This is because Regexp keeps track of the lastIndex when a new match is found.