Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Last active October 1, 2015 12:48
Show Gist options
  • Save tbranyen/1995492 to your computer and use it in GitHub Desktop.
Save tbranyen/1995492 to your computer and use it in GitHub Desktop.
Get all the argument names from a given function
// Get the argument names from a given function
Function.prototype.args = function() {
// First match everything inside the function argument parens
var args = this.toString().match(/function\s.*?\(([^)]*)\)/)[1];
// Split the arguments string into an array comma delimited
return args.split(", ").map(function(arg) {
// Ensure no inline comments are parsed and trim the whitespace
return arg.replace(/\/\*.*\*\//, "").trim();
}).filter(function(arg) {
// Ensure no undefineds are added
return arg;
});
};
// Potentially IE 6-friendly
// Get the argument names from a given function.
Function.prototype.args = function() {
var i, arg;
// Store ordered list of all the argument names.
var names = [];
// First match everything inside the function argument parens. Split the
// arguments string into an array comma delimited.
var args = this.toString().match(/function\s.*?\(([^)]*)\)/)[1].split(", ");
// Iterate over all arguments.
for (i = 0; i < args.length; i++) {
arg = args[i];
// Ensure no inline comments are parsed.
if (arg = arg.replace(/\/\*.*\*\//, "")) {
// Trim the whitespace and ensure no undefineds are added.
names.push(arg.replace(/^\s?|\s?$/g, ""));
}
}
return names;
};
// Normal arguments
function(lol, hi) {
}.args(); // ["lol", "hi"]
// Arguments with inline comments
function(/* hahaha */lol, /*wut wut */hi) {
}.args(); // ["lol", "hi"]
// No arguments
function() {
}.args(); // []
@Wilto
Copy link

Wilto commented Mar 8, 2012

please make this as jaquery plugin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment