-1

I have some functions like these:

  • function name_a(){}
  • function name_b(){}
  • function name_x(){}
  • function name_n(){}

I want to call all functions start with name_ with regex in javascript.

How can I do that?

6
  • 2
    meta.stackexchange.com/questions/66377/what-is-the-xy-problem Commented May 21, 2017 at 17:02
  • Curious. Are all of them global? Commented May 21, 2017 at 17:02
  • For global scope Object.keys(window).filter(key => typeof window[key] === 'function' && /^name_.*/.test(key)).forEach(funcName => window[funcName]()) But I'm quite sure this approach to original problem is wrong. Commented May 21, 2017 at 17:08
  • Why don't you just make an array of functions? Then you can call name[i](). Commented May 21, 2017 at 17:10
  • Why? What problem are you trying to solve? This seems like a convoluted, brittle way to do most anything. Commented May 21, 2017 at 17:44

2 Answers 2

1

Just for the kicks, here's something you can use. ES5, so IE>9 is required (could be tweaked for older browsers support, though).

/**
 * Calls functions of given target object with names matching given regex.
 *
 * @param {any} targetObject
 * @param {RegExp} nameRegex
 * @param {...any} functionsArguments
 *
 * @returns {any[]} The values returned by each function called.
 */
function callFunctionsMatching(targetObject, nameRegex, functionsArguments) {
      // make arguments into array, then splice
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
    var functionsArgs = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)).splice(2);

    return Object.getOwnPropertyNames(targetObject).filter(function (propertyName) {
        return typeof targetObject[propertyName] == 'function' && nameRegex.test(propertyName);
    }).map(function (functionName) {
        return targetObject[functionName].apply(targetObject, functionsArgs);
    });
}

Usage (demo JSBin here)

Global functions (window target object):

// setup some functions
function a1(a, b, c, d) { console.log('a1->', a, b, c, d); }
function b1(arg) { console.log('b1->', arg); }
window.c1 = console.log

// call every function ending with 1
callFunctionsMatching(window, /1$/, 'stuff', 1, 3, 4);

Output:

a1-> stuff 1 3 4
b1-> stuff
stuff 1 3 4

Objects functions (any object as target):

var person = {
  aa: function(x) { console.log('person.aa called with', x); return 'this is the return value of person.aa'; },
  aaz: function(x) { console.log('I shouldn have been printed'); }
};

var valuesReturned = callFunctionsMatching(person, /aa$/, 'some argument');

console.log('valuesReturned were', valuesReturned);

Output:

person.aa called with some argument
valuesReturned were ["this is the return value of person.aa"]

Example from the question:

function name_a(){ console.log('name_a called'); }
function name_b(){ console.log('name_b called'); }
function name_x(){ console.log('name_x called'); }
function name_n(){ console.log('name_n called'); }

callFunctionsMatching(window, /^name_/, 'args');

Output:

function name_a called
function name_x called
function name_n called
function name_b called
Sign up to request clarification or add additional context in comments.

Comments

0

This doesn't handle DOM objects, but if you have a plain object and simply want to search for all the functions matching a certain regex at one level, you could (optionally, showing executing each one in order):

function get_func_filter(obj, match) {
    var keys = Object.getOwnPropertyNames(obj);

    return keys.filter(function(func_name) {
        return typeof obj[func_name] === 'function'
               && match.test(func_name);
    });
}

var funcs = {
    'prop_a': 'value',
    'prop_b': 'value',
    'name_a': function(){console.log('name_a function called');},
    'name_b': function(){console.log('name_b function called');},
    'name_c': function(){console.log('name_c function called');},
    'not_name_a': function(){console.log('not_name_a function called');},
    'not_name_b': function(){console.log('not_name_b function called');},
};

// First, get the function names that match "starting with name_"
get_func_filter(funcs, /^name_/)
    // Then get each name
    .map(function(func_name) {
        // And execute it (the second)
        !funcs[func_name] || funcs[func_name]();
    }
);

https://jsfiddle.net/5vrfpmeq/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.