belyid belyid - 1 year ago 78
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?


I've changed the expression from
based on Bohemian response. But the error persists.

Answer Source

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


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);
              // this does not starts with /pt or /en
              // do some thing

Reference you are looking for

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download