≪ Today I learned. RSS購読
公開日
タグ
JavaScript
著者
ダーシノ

URLPatternを使ったパターンマッチングと実用例

URL Pattern APIを使うことで、URLのパーツ(プロトコル、ホスト名、パス、クエリパラメータ、ハッシュなど)をパターンマッチングで抽出できる実験的なWeb APIである。

このWeb APIを使うことでURLパターンマッチングがやりやすくなるので、ルーティングやアクセス制御などURLを扱う処理が簡潔に書けるようになる。

URLPatternの基本的な使い方

const pattern = new URLPattern({
  pathname: "/users/:id",
})

const url = "https://manage.example.com/users/123"

if (pattern.test(url)) {
  // match!!
  const result = pattern.exec(url)
  console.log(
    match.protocol.input, // "https:"
    match.hostname.input, // "manage.example.com"
    match.pathname.input, // "/users/123"
    match.pathname.groups.id, // "123"
  )
}

メソッド

プロパティ

実用例: ルーティング

const routes = [
  {
    pattern: new URLPattern({ pathname: "/posts/:slug" }),
    handler: (match) => {
      console.log(`Post slug: ${match.pathname.groups.slug}`)
    },
  },
  {
    pattern: new URLPattern({ pathname: "/magazine/:date(\\d{4}-\\d{2}-\\d{2})" }),
    handler: (match) => {
      console.log(`Magazine date: ${match.pathname.groups.date}`)
    },
  },
  {
    pattern: new URLPattern({ pathname: "/images/*", search: "size=:size" }),
    handler: (match) => {
      console.log(`Image path: ${match.pathname.input}`)
      console.log(`Image size: ${match.search.groups.size}`)
    },
  },
]


const url = "https://blog.example.com/posts/url-pattern"
// const url = "https://blog.example.com/magazine/2025-08-06"
// const url = "https://blog.example.com/images/test.jpg?size=large"

for (const route of routes) {
  if (route.pattern.test(url)) {
    const match = route.pattern.exec(url)
    route.handler(match)
    break
  }
}