belyid belyid - 1 month ago 11
AngularJS Question

Is it possible to use regular expressions to match url's on $urlRouterProvider?

I'm trying to use a regex expression to match all strings that don't start with "/pt/" or "/en/" in my routing config. They may or may not have additional text.

So I came up with this:

$urlRouterProvider.when('^(?!/(pt|en)/).*', function ($injector, $location) {
const path = $location.path();
$location.path('/pt' + path !== '' ? path : '/').replace();
});


Unfortunately this throws the error:
Invalid parameter name '.' in pattern '^(?!/(pt|en)/).*'


What is the right way to use regular expressions in this scenario?

EDIT

I've changed the expression from
'{(?!\/(pt|en)\/).*}'
to
'^(?!/(pt|en)/).*'
based on Bohemian response. But the error persists.

Answer

when method does not have the $injector and $location services.use rule() instead,

Change the regex to /^(?!\/(pt|en)).*/ to meet your requirement.

Check the regexp here

rule() for custom url handling

Parameters:

handler Function A function that takes in the $injector and $location services as arguments. You are responsible for returning a valid path as a string.

app.config(function ($urlRouterProvider) {
    $urlRouterProvider.rule(function ($injector, $location) {
           //what this function returns will be set as the $location.url
            var path = $location.path(), normalized = path.toLowerCase();
            if ('/pt.asd'.match(/^(?!\/(pt|en)).*/) == undefined) {
                // this starts with /pt or /en
                // $location.replace().path(normalized);
            }
            else
            {
              // this does not starts with /pt or /en
              // do some thing
            }
      });
})

Reference you are looking for

Comments