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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With