4

I have a string comprised of my name christiancattano and a regex search pattern defined as such

/(cattano|cattan|attano|chris|catta|attan|ttano|chri|hris|catt|atta|ttan|tano|chr|hri|ris|cat|att|tta|tan|ano)+/ig

In regex101 if I enter my search pattern in the top bar, and enter verbatim, christiancattano into the test string box it will hightlight chrisand cattano. This is the behaviour I am expecting.

In my javascript code if I run the following lines

var regExPattern: string = '(cattano|cattan|attano|chris|catta|attan|ttano|chri|hris|catt|atta|ttan|tano|chr|hri|ris|cat|att|tta|tan|ano)+';

var regExObj: RegExp = new RegExp(regExPattern, 'g');

var match: string[] = regExObj.exec('christiancattano');

console.log(`match: ${match}`);

I receive this output

match: chris,chris

Why is it that regex101 shows my matches being what I expect, chris and cattano, but my Javascript code is producing a different result?

Chris
  • 443
  • 5
  • 25
  • 3
    Use `match`: `'christiancattano'.match(regExObj)` – Wiktor Stribiżew Apr 17 '17 at 18:36
  • 3
    In Javascript, when you execute a RegExp with the `g` modifier, it just returns one match at a time. You have to call it in a loop to get all the matches. Remove the modifier. – Barmar Apr 17 '17 at 18:39
  • @WiktorStribiżew my man! You did it again! Thank you so much! I've just read into the differences between string.match(), and regex.exec(), and I see where I went wrong in attempting to get a string[] of my matches. Thank you again so much for your help today! – Chris Apr 17 '17 at 18:49

1 Answers1

3

RegExp#exec() only returns a single match object, even if you use a regex with the g modifier.

You may use String#match with a regex with the g modifier to get all match values:

var match: string[] = 'christiancattano'.match(regExObj)  
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563