Skip to content

Function: extractRouteParams()

API / @xmachines/play-router / extractRouteParams

function extractRouteParams(pathname, pattern): Record<string, string>;

Defined in: router-sync.ts:117

Reads the named path parameters of a URL, with the URLPattern API.

The function takes the string of the pattern directly. Use it when you know the pattern already. For a read through the lookup of a state ID, see RouterBridgeBase.extractParams.

The object of the return holds no undefined value. Such a value comes from an optional segment without a match, for example /settings against /settings/:section?.

The function normalizes the pattern with the rules of the match in RouteMap: a name with a hyphen, such as :cat-id, becomes :cat_id for URLPattern. It then maps each group name back to the original param name. Therefore /docs/123 against /docs/:cat-id gives { "cat-id": "123" }.

The function decodes each percent sequence of a value (john%20doejohn doe), as a framework router does, for example vue-router. It keeps a malformed sequence raw.

Parameters

ParameterTypeDescription
pathnamestringThe concrete URL pathname, for example /profile/alice
patternstringThe template of the URL pattern, for example /profile/:username

Returns

Record<string, string>

The record of the parameter values of the read, or {} for a static pattern.

Throws

When URLPattern is absent and the pattern holds a parameter.

Example

import { extractRouteParams } from "@xmachines/play-router";
extractRouteParams("/profile/alice", "/profile/:username");
// → { username: "alice" }
extractRouteParams("/settings", "/settings/:section?");
// → {} — the optional param is absent, and the object holds it not