URLPattern matches complete URLs or individual URL components.
const users = new URLPattern({ pathname: "/users/:id" });
users.test({ pathname: "/users/42" }); // true
users.exec({ pathname: "/users/42" }).pathname.groups.id; // "42"Construction accepts a pattern string plus optional base URL, or a dictionary
with protocol, username, password, hostname, port,
pathname, search, hash, and baseURL. The
ignoreCase option applies case-insensitive matching.
Pattern syntax
| Syntax | Meaning |
|---|---|
:name | Named segment capture. |
:name(regex) | Named custom regular expression. |
(regex) | Unnamed custom regular expression. |
* | Full wildcard. |
{...} | Group. |
?, +, * | Optional or repeating modifier. |
\x | Escaped literal. |
const api = new URLPattern("https://*.example.com/api/:resource");
api.exec("https://v2.example.com/api/widgets")
.pathname.groups.resource; // "widgets"
const numeric = new URLPattern({ pathname: "/items/:id(\\d+)" });
numeric.test({ pathname: "/items/123" }); // true
const relative = new URLPattern("/items/:id", "https://example.com/");
relative.test("https://example.com/items/7"); // truetest() returns a boolean. exec() returns null or a result with each
component’s input and capture groups. Read-only component attributes expose
the compiled pattern, and hasRegExpGroups identifies explicit regex groups.