# URLPattern

> The `URLPattern` JS object matches URLs against patterns.

## How do I match URL routes with URLPattern in JavaScript?

The object that matches URLs or their parts against patterns with named groups and wildcards, for example '/users/:id'. Useful for routing in service workers and client-side routers.

- Topic: Navigation in Browser
- Type: object
- Browser support: Chrome 95+, Chrome Android 95+, Edge 95+, Firefox 142+, Firefox Android 142+, Safari 26+, Safari iOS 26+

## Example

Wrong:

```js
const parts = location.pathname.split('/');
const id = parts[2];
```

Right:

```js
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.

## Common mistakes

- Forgetting that `exec()` returns `null` when the URL does not match.

## Key points

- Route params are read from `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.
- Code for browsers without `URLPattern` has a fallback or polyfill.

## Interview questions

### What syntax does URLPattern use?

It uses path-to-regexp style syntax: ':name' for named groups, '*' for wildcards and '{...}?' for optional parts.

### Can URLPattern match the query string?

Yes. Each URL part, such as `search` and `hash`, has its own pattern, but it matches the raw string, so parameter order matters.

## Related cards

- [URL.canParse()](https://wonderium.dev/js/url-can-parse.md)
- [navigation](https://wonderium.dev/js/navigation.md)
- [Router](https://wonderium.dev/web/router.md)
- [URL](https://wonderium.dev/web/url.md)
- [RegExp](https://wonderium.dev/js/regexp.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/url-pattern
- Last updated: 2026-11-25
