I've run into a odd problem. When I try to test if path-to-regexp
will match a given path I will not get a result when expected, if I pass the input string from a variable. But if I hard-code the string directly (i.e. the very same string that is being printed to the console when printing the variable) it works?
Any idea what might be going on here?
I build a little prototype you can try out
And here is the code example:
import { match } from "path-to-regexp";
const esc = require("./escapeRegexInPath");
const pattern = new RegExp("[0-9]*");
// Does the pattern match "123"
console.log({ patternTest: pattern.test("123") });
// => {patternTest: true}
// The escape function will escape special characters
const escapedRegex = esc(pattern);
console.log({ escapedRegex });
// => {escapedRegex: "[0-9]\*"}
// This matcher is passed the escaped regex as a variable
const matcher = match(`:entityId(${escapedRegex})`);
// And it fails to match anything with input "123"
console.log({ matcher: matcher("123") });
// {matcher: false}
// This matcher is passed a hardcoded regex
// And it succesfully matches with input "123"
const matcher2 = match(`:entityId([0-9]\*)`);
console.log({ matcher2: matcher2("123") });
// => {matcher2: Object}