Regular Expression to get parameter list from function definition

Do as following:

var ar = str.match(/\((.*?)\)/);
if (ar) {
  var result = ar[0].split(",");
}

Remember ? after * does a non greedy find


Preface: By far, the best way to handle this is to use a JavaScript parser rather than trying to do it with a single regular expression. Regular expressions can be part of a parser, but no one regular expression can do the work of a parser. JavaScript's syntax (like that of most programming languages) is far too complex and context-sensitive to be handled with a simple regular expression or two. There are several open source JavaScript parsers written in JavaScript. I strongly recommend using one of those, not what's below.


The easiest thing would be to capture everything in the first set of parens, and then use split(/\s*,\s*/) to get the array.

E.g.:

var str = "function(   one  ,\ntwo,three   ,   four   ) { laksjdfl akjsdflkasjdfl }";
var args = /\(\s*([^)]+?)\s*\)/.exec(str);
if (args[1]) {
  args = args[1].split(/\s*,\s*/);
}
console.log("args: ", args);

How the above works:

  1. We use /\( *([^)]+?) *\)/ to match the first opening parenthesis (\( since ( is special in regexes), followed by any amount of optional whitespace, followed by a capture group capturing everything but a closing parenthesis (but non-greedy), followed by any amount of optional whitespace, followed by the closing ).

  2. If we succeed, we split using /\s*,\s*/, which means we split on sequences which are zero or more whitespace characters (\s*) followed by a comma followed by zero or more whitespace characters (this whitespace thing is why the args in my example function are so weird).

As you can see from the example, this handles leading whitespace (after the ( and before the first argument), whitespace around the commas, and trailing whitespace — including line breaks. It does not try to handle comments within the argument list, which would markedly complicate things.

Note: The above doesn't handle ES2015's default parameter values, which can be any arbitrary expression, including an expression containing a ) — which breaks the regex above by stopping its search early:

var str = "function(   one  ,\ntwo = getDefaultForTwo(),three   ,   four   ) { laksjdfl akjsdflkasjdfl }";
var args = /\(\s*([^)]+?)\s*\)/.exec(str);
if (args[1]) {
  args = args[1].split(/\s*,\s*/);
}
console.log("args: ", args);

Which brings us full circle to: Use a JavaScript parser. :-)