Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex101 and Js regex search showing different results

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?

like image 735
Chris Avatar asked Oct 25 '25 08:10

Chris


1 Answers

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)  
like image 123
Wiktor Stribiżew Avatar answered Oct 27 '25 22:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!