Regex in a switch case

Asked

Viewed 261 times

2

About

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

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

Problem

When he accesses the '/profile/edit/1' I want him to take any number where there is '1' because my url is '/profile/edit/:id', I tried using regex but I was not very successful. Would anyone have any idea?

1 answer

4

switch in Javascript only works with constants. To test against patterns you would have to use ifs even more because 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 bars and use ^ and $ to ensure that you are testing against the entire string.


That said, it is quite possible that you already have some functionality ready in Angular to do this URL routing. My response was made by assuming pure Javascript.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.