In JavaScript, you can extract the parameter names of a function dynamically by converting the function into a string and processing its contents.
- The toString() method converts a function into its string representation.
- Regular expressions can remove comments, function bodies, and default values.
- The parameter section can then be extracted and converted into an array.
- This approach works with regular functions and arrow functions.
Using toString() and Regular Expressions
The toString() method returns the source code representation of a function. We can process this string to extract the function's parameter names.
Working:
- Convert the function into a string using toString().
- Remove comments, the function body, and the arrow (=>) syntax.
- Locate the opening ( and closing ) surrounding the parameters.
- Extract the parameter section and split it using commas.
- Remove default values and empty parameters.
- Return the parameter names as an array.
function getParams(func) {
// Convert the function to a string
let str = func.toString();
// Remove comments, function body and arrow syntax
str = str.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/\/\/(.)*/g, '')
.replace(/{[\s\S]*}/, '')
.replace(/=>/g, '')
.trim();
// Find the starting position of parameters
let start = str.indexOf("(") + 1;
// Find the ending position of parameters
let end = str.length - 1;
// Extract and split parameters
let result = str.substring(start, end).split(",");
let params = [];
result.forEach(element => {
// Remove default values
element = element.replace(/=[\s\S]*/g, '').trim();
// Add non-empty parameters
if (element.length > 0) {
params.push(element);
}
});
return params;
}
// Test functions
let fun1 = function (a) { };
function fun2(a = 5 * 6 / 3, b) { }
let fun3 = (a, /*
*/
b, // comment
c) => { };
// Display parameter names
console.log(`List of parameters of ${fun1.name}:`,
getParams(fun1));
console.log(`List of parameters of ${fun2.name}:`,
getParams(fun2));
console.log(`List of parameters of ${fun3.name}:`,
getParams(fun3));
Output
List of parameters of fun1: [ 'a' ] List of parameters of fun2: [ 'a', 'b' ] List of parameters of fun3: [ 'a', 'b', 'c' ]
- func.toString() gets the function's source code as a string.
- replace() removes comments, the function body, and arrow-function syntax.
- substring() extracts the portion containing the parameters.
- split(",") separates individual parameters.
- replace() removes default values such as a = 10.
- The resulting parameter names are stored in the params array.