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*/);
}
snippet.log("args: " + JSON.stringify(args));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
How the above works:
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 )
.
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.
Side note: Be sure to test on your target browsers, Function#toString
returning some form of the source code is a non-standard feature. It's broadly supported (in desktop browsers), but not standard. Note that some browsers will include comments, others will not; if someone includes comments in the function arguments, it could well mess up your parsing of them. You might kick around the Prototype source code for its Function#argumentNames extension, as they've already been down this road...