0

Test Strings:

first.second.third.last

Match result:

first
second
third
fourth

I was able to match only for first.second using pattern .*(?=\.)|(?<=\.).*.

When I use this in console "licence.name".match(/(.*(?=\.))|(?<=\.).*/), it returns an Array with licence, on regex101.com the result is different it match produces:

match 1 licence

match 2 ''

match 3 name

regex101 match

console match

Why is the match result different for JavaScript and regex101.com?

What I want is, in JavaScript match() function to return the desired match array.

qiAlex
  • 4,290
  • 2
  • 19
  • 35
HarshvardhanSharma
  • 754
  • 2
  • 14
  • 28

1 Answers1

-1

You have to add the modifier g to your regex, to retrive all results and not only the first match. On the first picture of regex101.com you can see that the service applies gm as modifiers to the regex. But the m is only necessary when you have multi line strings and you want to match also results on other lines.

"licence.name".match(/(.*(?=\.))|(?<=\.).*/g);
//["licence", "", "name"]

Have a look at the msdn article of String.prototype.match:

If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec(). The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.

If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.

And-y
  • 1,519
  • 2
  • 22
  • 33