Vue Routing and Regex Patterns

Viewed 261

I'm using Vue and recently introduced a route with a parameter.

const routes = [
  {
    path: "/:lang(^$|^es$|^pt$|^cn$)",
    name: "Home",
    component: Page,
  },
  {
    path: "/privacy",
    name: "Privacy",
    component: Privacy,
  },
  {
    path: "*",
    name: "NotFound",
    component: NotFound,
  }
];

I want the route to trigger when one of the following conditions is met.

  1. lang is empty
  2. lang is either es or pt or cn but no combinations of those.

Everything else should go to the NotFound route

The regex I'm using above works on the javascript engine of https://regexplanet.com

I tried all sorts and variations to make it work in Vue but to no avail so far.

1 Answers

I believe the path you need is:

path: "/:lang(|es|pt|cn)",

There's a routing tester here that uses the same library as Vue:

https://forbeslindesay.github.io/express-route-tester/

Make sure you're testing against path-to-regexp 0.1.7.

The problem is that the whole path gets converted to a RegExp, not just the bits in the brackets. So your ^ are never going to match anything. Try putting your original path into the testing tool to see how it compiles. The generated RegExp already contains its own ^ and $ but they are relative to the whole path, not just the parameter you're trying to match.

Related