diff --git a/index.d.ts b/index.d.ts index 0f731d00..382f76f1 100644 --- a/index.d.ts +++ b/index.d.ts @@ -58,6 +58,7 @@ export type QContext = { }; export type GenerateOptions = { includeRoot: boolean; + replaceRegexGroups: boolean; }; export type RouterOptions = ResolveOptions & { linksSelector?: string }; declare class Navigo { diff --git a/src/index.ts b/src/index.ts index c93384bd..f51eee14 100644 --- a/src/index.ts +++ b/src/index.ts @@ -312,7 +312,19 @@ export default function Navigo(appRoute?: string, options?: RouterOptions) { if (data) { for (let key in data) { result = result.replace(":" + key, data[key]); + + // If regex group replacement is enabled, search + // for named-regex parameter groups + if (options?.replaceRegexGroups === true) { + const regexEscapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + + // Note that this won't handle regex groups that contain sub-groups + // e.g. /(?(:?example)?) + const keyRegex = new RegExp(`\\(\\?\\<${regexEscapedKey}\\>[^\\(^\\)]+\\)`, "g"); + result = result.replace(keyRegex, data[key]); + } } + } result = !result.match(/^\//) ? `/${result}` : result; } diff --git a/src/middlewares/setLocationPath.ts b/src/middlewares/setLocationPath.ts index 3210796c..475cb205 100644 --- a/src/middlewares/setLocationPath.ts +++ b/src/middlewares/setLocationPath.ts @@ -1,15 +1,14 @@ import { QContext } from "../../index"; import { getCurrentEnvURL } from "../utils"; -export default function setLocationPath(context: QContext, done: () => void): void { - - const { currentLocationPath, instance } = context; - - if (typeof currentLocationPath === "undefined") { - context.currentLocationPath = context.to = getCurrentURLPath(instance.root); +export default function setLocationPath(context: QContext, done) { + if (typeof context.currentLocationPath === "undefined") { + context.currentLocationPath = context.to = getCurrentEnvURL( + context.instance.root + ); } - - context.currentLocationPath = instance._checkForAHash(currentLocationPath); - + context.currentLocationPath = context.instance._checkForAHash( + context.currentLocationPath + ); done(); }