Regex101 and Js regex showing different results

I have a string consisting of my name christiancattano

and a regex search pattern defined as

/(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 type verbatim, christiancattano

in the test string box, it will be hightlight chris

and cattano

. This is the behavior I expect.

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 am getting this output

match: chris,chris

      

Why does regex101 show my matches are what I expect chris

and cattano

but my Javascript code produces a different result?

+3


source to share


1 answer


RegExp#exec()

only returns one match object, even if you are using a modifier regex g

.

You can use String#match

with modifier regex g

to get all match values:



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

      

+2


source







All Articles