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(); // []
@tbranyen
Copy link
Author

tbranyen commented Mar 7, 2012

Please Do Not Use This Ever

Unless you really really really really really need to

@Wilto
Copy link

Wilto commented Mar 7, 2012

Looks great! Can’t wait to use this on my next project!

@tjfontaine
Copy link

javascript kwargs here I come

@emilylaguna
Copy link

Now I can enforce strict argument names! Thanks Tim!

@csnover
Copy link

csnover commented Mar 7, 2012

p.s. those are called parameters :)

@emilylaguna
Copy link

Not in my world.

@pifantastic
Copy link

I'M HAVING YRUBLE GETTING THS 2 WORK ON MY TALKBOY PRO. PLZ FIX.

WAITNG UR REPLY.

@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