sutoiku / formula.js

JavaScript implementation of most Microsoft Excel formula functions
Other
2.14k stars 293 forks source link

REGEXEXTRACT #14

Closed mlconnor closed 10 years ago

mlconnor commented 10 years ago

I noticed that REGEXEXTRACT can't handle capture groups. Google handles this as you can see here https://support.google.com/docs/answer/3098244

In their example, text = "(Content) between brackets" regex = '(([A-Za-z]+))'

returns 'Content'

I think that if the match call returns more than one element in the array then the first value should be returned instead of the entire match.

Current impl

    Formula.REGEXEXTRACT = function (text, regular_expression) {
      var match = text.match(new RegExp(regular_expression));
      return match ? match[0] : null;
    };

Proposed

    Formula.REGEXEXTRACT = function (text, regular_expression) {
      var match = text.match(new RegExp(regular_expression));
      return match ? (match[match.length > 1 ? match.length - 1 : 0]) : null;
    };
mlconnor commented 10 years ago

actually, if you wanted to make it just like google docs, it would be...

    Formula.REGEXEXTRACT = function (text, regular_expression) {
      var match = text.match(new RegExp(regular_expression));
      return match ? (match.length == 1 ? match[0] : match.slice(1)) : null;
    };
jalateras commented 10 years ago

Updated source so that it works as expected.

mlconnor commented 10 years ago

thank you sir! I love killing forks. I love FormulJS, great work.