[JS] Regex related functions usage

String.prototype.match()

  • Result format depends on whether the regex has ‘g’ flag.
  • Use for a single match or global matches without group information.
let x = '123abcdef123';
x.match(/(123)/);
// [full_matched, 
//  group1, group2, ..., groupN, 
//  index: index_of_first_match, 
//  input: original_input_string, 
//  groups: named_groups] 

// ["123", 
//  "123", 
//  index: 0, 
//  input: "123abcdef123", 
//  groups: undefined] 

x.match(/(123)/g); 
// NO GROUPS IN RESULTS!!! 
// [first_match, second_match, ..., Nth match] 
// ["123", "123"]

String.prototype.matchAll()

  • Use for global matches where group results are needed.
let x = '123abcdef123'; 
[...x.matchAll(/(123)/g)]; 
// [[first_full_matched, 
//  group1, group2, ..., groupN, 
//  index: index_of_first_match, 
//  input: original_input_string, 
//  groups: named_groups], 
//  [second_full_matched, ...], ...]

RegExp.prototype.exec()

  • Similar use case as String.prototype.match(), but when a sticky flag is used, the regex becomes stateful, calling exec() multiple times on the same string will continue the matching. If global matching is needed, String.prototype.matchAll is preferred for its cleaner code.

RegExp.prototype.test()

String.prototype.search()

  • Both can be used for testing if a string satisfies a regex.