Loading...
const parts = location.pathname.split('/');
const id = parts[2];const pattern = new URLPattern({ pathname: '/users/:id' });
const match = pattern.exec(location.href);
const id = match?.pathname.groups.id;The pattern names the parameter and returns null for other routes, instead of trusting a fixed index.
exec() returns null when the URL does not match.result.pathname.groups, not parsed by hand with split('/').test() is used when only a yes/no answer is needed, exec() when the groups are needed.URLPattern has a fallback or polyfill.It uses path-to-regexp style syntax: ':name' for named groups, '*' for wildcards and '{...}?' for optional parts.
Yes. Each URL part, such as search and hash, has its own pattern, but it matches the raw string, so parameter order matters.