Yaroslaw Bolyukin Yaroslaw Bolyukin - 6 months ago 21
Node.js Question

Strange RegExp behavior in JavaScript

I need to capture every

%{string}
sequience in a string.
I am created a RegExp:
/[^%]*(%{[^}]+})?/g
,
which works correctly on string
Lorem %{ipsum} dolor %{sit} amet adipiscing aenean %{consectetuer}
on regex101.com (https://regex101.com/r/aB2xL5/1), but incorrect in JS:

var a='Lorem %{ipsum} dolor %{sit} amet adipiscing aenean %{consectetuer}'.match(/[^%]*(%{[^}]+})?/g);

console.log(a); //['Lorem %{ipsum}', ' dolor %{sit}', ' amet adipiscing aenean %{consectetuer}', '']

What i am doing wrong?

What i need:

Input string: 'abc %{def} ghi %{jkl}'
Output array: ['%{def}','%{jkl}']

Answer

As said in the comments, don't access the whole match which, even on regex101, contains more than you need, but rather access the first group of the match.

To do so, use Regex.prototype.exec instead of String.prototype.match:

var regex=/[^%]*(%{[^}]+})?/g;
var data='Lorem %{ipsum} dolor %{sit} amet adipiscing aenean %{consectetuer}';
var result=[];
var match;
while (match = regex.exec(data)) {
  result.push(match[1]);  // match the first group of the result
}

Edit : I just saw Thomas' comment, which is much better than this solution. I'll leave it here because it does indeed solve your problem and explains how to capture groups, but you should use his regex.