URL Pattern API
Это инструмент для сопоставления URL на основе шаблонов. Допустим, есть URL https://example.com/products/123. И нужно сопоставить его с шаблоном https://example.com/products/:id. Это можно сделать так:
const urlPattern = new URLPattern({ pathname: "/products/:id" });const url = new URL("https://example.com/products/123");console.log(urlPattern.test(url)); // trueКроме теста соответствия урла шаблону, можно ещё и извлечь соответствующие параметры:
const urlPattern = new URLPattern({ pathname: "/products/:id" });const url = new URL("https://example.com/products/123");const result = urlPattern.exec(url);console.log(result.pathname.groups.id); // "123"Самый очевидный юзкейс URLPattern — клиентский роутер, который проверяет соответствие текущего урла паттерну, по которому показывается нужный контент. Пример в React:
<Router> <Route path="/"> <Home /> </Route> <Route path="/about"> <About /> </Route> <Route path="/messages/:id"> <Messages /> </Route></Router>function Route({ path, children }) { const baseURL = window.location.origin; const pattern = new URLPattern({ pathname: path, baseURL }); const match = pattern.test(currentPath);
if (!match) { return null; }
return children;}Помимо pathname URLPattern умеет определять все остальные части урла: hash, hostname, password, port, protocol, search, username.
Работает пока что только в Chromium, но полифиллится.