Regex on a switch case

2

About

I have a switch that takes care of activating my menus from their address on the website.

        switch($location.path()){
                case '/perfil':
                    $scope.menuAtivo.perfil = 'active';
                    break;
                case '/perfil/editar/1':
                    $scope.menuAtivo.perfil = 'active';
                    break;
        }

Problem

. Would anyone have any ideas?

    
asked by anonymous 22.08.2014 / 20:44

1 answer

4

switch in Javascript only works with constants. To test against defaults you would have to use ifs anyway, especially since you need to be explicit about the order in which the tests will be done ..

var path = $location.path();
var m;
if((m = path.match(/^\/perfil\/$/)){
    //nesse caso nao precisa de regex pra falar a verdade
}else if((m = path.match(/^\/perfil\/editar\/(\d+)$/))){
    var id = m[1];
}

Remember that to use regex you need to escape the slashes and use ^ and $ to ensure that you are testing against the entire string.

That said, it's quite possible that I already have some functionality ready in the Angular to do this URL routing. My answer was made assuming pure Javascript.

    
22.08.2014 / 20:51