Answers for "regex test vs match"

0

regex test vs match

// Syntax
  
  'string'.match(/regex/);
  /regex/.test('string');

// Explanation 1

  match() method to extract the string.
  test() to return boolean.

  // Source: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/extract-matches

// Explanation 2

  // Don't forget to take into consideration the global flag in your regexp :

  var reg = /abc/g;
  !!'abcdefghi'.match(reg); // => true
  !!'abcdefghi'.match(reg); // => true
  reg.test('abcdefghi');    // => true
  reg.test('abcdefghi');    // => false <=


  // => This is because Regexp keeps track of the lastIndex when a new match is found.
Posted by: Guest on August-14-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language