Search code examples
javascriptexpresspath-to-regexp

The "^" character does not interpreted as a start of line in regular expression provided to the route handler


I have one issue with express I want to use "^" as we use it in Javascript regex but unfortunately it does not work...
so here i added "^" to give pattern to the storeName path parameter::

router.get(
  "/stores/:storeName(^[a-zA-Z0-9_-][a-zA-Z0-9_-]{0,})",
  async(req, res) => {
    console.log("here");
  }
);

This route is not mach this route

"http://localhost:3000/stores/saidm"

nor this

"http://localhost:3000/stores/^saidm"

I expected the route to be matched for at least one of this paths


Solution

  • Based on the example in the documentation, I think the regexp is automatically anchored to match the entire route parameter. So you don't need ^ or $.

    Try

    router.get(
      "/stores/:storeName([\\w-]+",
      async(req, res) => {
        console.log("here");
      }
    );
    

    Note that \w matches letters, numbers, and underscore. And + is the quantifier to match 1 or more of the preceding pattern.