0

just read the code below in angular source code. It's part of dependency injection. Basically this is more about regular expression.

var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var $injectorMinErr = minErr('$injector');
function annotate(fn) {
  var $inject,
      fnText,
      argDecl,
      last;

  if (typeof fn === 'function') {
    if (!($inject = fn.$inject)) {
      $inject = [];
      if (fn.length) {
        fnText = fn.toString().replace(STRIP_COMMENTS, '');
        argDecl = fnText.match(FN_ARGS);
        forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
          arg.replace(FN_ARG, function(all, underscore, name){
            $inject.push(name);
          });
        });
      }
      fn.$inject = $inject;
    }
  } else if (isArray(fn)) {
    last = fn.length - 1;
    assertArgFn(fn[last], 'fn');
    $inject = fn.slice(0, last);
  } else {
    assertArgFn(fn, 'fn', true);
  }
  return $inject;
}

I try to run the code below in my chrome console, what confused me is where is the second element coming from?

As for my understanding, I think it should just return the first element which is function testService(testService, loginService).

var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var testFunc = function testService (testService, loginService) {
    loginService.login();
}
var str = testFunc.toString();
var arr = str.match(FN_ARGS);
console.log(arr);
//["function testService(testService, loginService)", "testService, loginService"]

Could anybody help me about this, thx.

1 Answer 1

1

match returns the entire string if it matches at index 0. The other indices represent regular expression groups that have matched. You can declare a group within a regex with parenthesis. In this case, the group is ([^\)]*).

Sign up to request clarification or add additional context in comments.

1 Comment

Thx for you help, just check the MDN document here. : )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.