Skip to content

Instantly share code, notes, and snippets.

@flakd
Last active December 20, 2015 03:28
Show Gist options
  • Select an option

  • Save flakd/6063382 to your computer and use it in GitHub Desktop.

Select an option

Save flakd/6063382 to your computer and use it in GitHub Desktop.
JS get parameter names dynamically
RIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function getParamNames(func) {
var funStr = func.toString();
funStr = funStr.replace(STRIP_COMMENTS, '');
return funStr.slice(funStr.indexOf('(')+1, funStr.indexOf(')')).match(/([^\s,]+)/g);
}
Example usage:
getParamNames(getParamNames) // returns ['func']
getParamNames(function (a,b,c,d){}) // returns ['a','b','c','d']
getParamNames(function (a,/*b,c,*/d){}) // returns ['a','d']
Edit: I also note vikasde wants the parameter values in an array also. This is already provided in a local variable named arguments.
excerpt from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments:
The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:
var args = Array.prototype.slice.call(arguments);
If Array generics are available, one can use the following instead:
var args = Array.slice(arguments);
share|edit|flag
edited Jul 8 at 13:40
answered Mar 29 '12 at 11:30
Jack Allan
843612
3
Note this works on all browsers – Jack Allan Mar 29 '12 at 11:41
Well done ;-) Thanks. – Alex Yaroshevich Feb 1 at 23:32
5
Note that this solution may fail because of comments and spaces - for example: var fn = function(a /* fooled you)*/,b){}; will result in ["a", "/*", "fooled", "you"] – bubersson Feb 2 at 7:57
This and @Lambder's angular solution get the parameter names, but how do you get the values? – CWSpear May 3 at 19:45
@bubersson You could use this in conjunction with the AngularJS code to strip comments shown in Lambder's answer in order to avoid comments breaking this. – JBarnes Jul 3 at 13:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment