URLPattern Matches Route Patterns

Compile route templates once and exec or test requests against them, extracting named groups and rejecting wrong hosts without hand-parsing.

JavascriptData Fetching

Code

snippet
// URLPattern 把路由模板编译成可复用的匹配器
const route = new URLPattern({ pathname: '/users/:id/posts/:postId' });

const match = route.exec({ pathname: '/users/42/posts/7' });
console.log('matched:', match !== null);
console.log('id:', match.pathname.groups.id, 'postId:', match.pathname.groups.postId);

// 不匹配返回 null,而不是抛错
console.log('missing segment:', route.exec({ pathname: '/users/42/posts' }));

// test 只判断是否命中,不提取组
console.log('test ok:', route.test({ pathname: '/users/9/posts/1' }));
console.log('test fail:', route.test({ pathname: '/users/9/comments/1' }));

// 段内可用正则约束:扩展名只放行 png/jpg
const files = new URLPattern({ pathname: '/static/:name.:ext(png|jpg)' });
console.log('image ext:', files.exec({ pathname: '/static/logo.png' }).pathname.groups.ext);
console.log('rejected svg:', files.exec({ pathname: '/static/logo.svg' }));

// 用完整模板绑定协议与主机名:异源请求直接不命中
const api = new URLPattern('https://api.example.com/v1/:resource');
console.log('bound host:', api.test('https://api.example.com/v1/orders'));
console.log('other host:', api.test('https://evil.example.com/v1/orders'));

Compile once, match many

new URLPattern({ pathname: ‘/users/:id/posts/:postId’ }) builds a reusable matcher. exec returns a result whose pathname.groups carries id and postId (42 and 7 in the demo), while a missing segment yields null rather than an error.

test versus exec

test(…) answers yes/no only — the demo shows test ok: true and test fail: false for a mismatched posts/comments path — while exec additionally extracts the named groups.

Constraints and origin binding

A segment can carry a regex: :ext(png|jpg) accepts logo.png and rejects logo.svg. And a full-string pattern (‘https://api.example.com/v1/:resource’) binds protocol and host, so the evil.example.com request fails the test — no hand-parsed origin checks needed.

Interactive Tools for This Topic

FAQ

What does exec return when the pattern does not match?
null — no exception is thrown, so callers just test for a missing result.
How does URLPattern reject a different host?
Compile the pattern from a full template string including scheme and host; requests against another origin then fail test() without any manual origin comparison.