How can I use RegEx to solve this efficiently

I have an object.

var NavigationController = function(config) {

    if(!config) {
        config = {};
    }

    if(!config.routes) {
        config.routes = {};
    }

    var getControllerByPath = function(path) {
        // I need to get Controller (UserController) if path matches in routes (/user/me)
    };
}

I can use this as...

var navController = new NavigationController({
    routes : {
        '/user/:action' : 'UserController',
        '/app/:action' : 'AppController',
        '/file/:action' : 'FileController',
        '/feedback/:action' : 'FeedbackController'
    }
});

navController.navigate(req, res);

At the moment, I am generating regex string for each route and then matching it to the path string, it works but is that efficient?

Regex seems like a great way to go for this problem. You could scan through and look for / and : but you can also write your regex without backtracking and that could help you in performance.

If you try to make it performant you'll spend a lot of time writing algorithms that may not be necessary at all...are you sure this is where your app needs performance improvements? Pre-optimization is often one of the most common mistakes and your best bet may be to get your logic in your app and then try to figure out which parts are slow and optimize those.

I hope this helped!

EDIT: an example of the kind of regex I'm talking about:

Suppose the problem is to match everything in a string up to the letter k, most people would suggest:

.*k

But this matches strings like: "hijk" and "hijkhijkh" (matches hijk, hijkhink respectively). This is because this regex is really saying "grab everything, see if the last character is a k. If it is not, drop that character and work backward until it becomes true or there are no more characters left."

If you want to match the first k, you could do something like this:

.*?k

This says: "grab a character at a time, see if it matches the pattern (ends with k). If not, keep grabbing until the token matches or until there is nothing left to match and no match is found."

You can leverage this to grab one character at a time...the greedy operator scans through the string right away, so O(n) to begin with. The latter version I introduced could have a much better best-case scenario because it works until the first match is found...but you should really try these out with your app and performance test them if this is a bottleneck since it's really dependent on the kind of data your app works with on the average case.