今日已更新 306 条资讯 | 累计 33763 条内容
关于我们

Stop Writing Regex to Match URLs — The Browser Already Can

Parsa Jiravand 2026年08月20日 14:53 2 次阅读 来源:Dev.to

Priya was three paragraphs into rewriting a support ticket when the page flashed and her draft reverted to what it had looked like an hour earlier. She hadn't refreshed. Nobody had. The service worker had. It was running a cache-first strategy for ticket pages — fetch once, serve from cache after that, so the dashboard felt instant on a flaky connection. The intent was to cache /tickets/482 , the read-only view, and leave /tickets/482/edit alone, since an edit form is exactly the page you never want served stale. Here's the line that decided which was which: const isTicketView = /^ \/ tickets \/\d +/ . test ( pathname ); Spot it yet? Read it once more before you scroll. The missing character was $ /^\/tickets\/\d+/ anchors the start of the string — ^ — but never anchors the end. So it matches /tickets/482 . It also matches /tickets/482/edit , /tickets/482/history , and /tickets/482-anything-at-all , because "one or more digits after /tickets/ " is true of all of them. The regex was never wrong about what it checked. It just never checked enough. The one-character fix is obvious once you see it: const isTicketView = /^ \/ tickets \/\d +$/ . test ( pathname ); Ship that and you'll hit the next edge case within a week: a trailing slash ( /tickets/482/ ) now fails to match, because $ demands nothing comes after the digits — not even a slash. Add \/? before the $ and you've fixed that one. Then someone deep-links to /tickets/482?tab=history and the query string breaks the anchor again, because pathname on some code paths actually holds the full URL. Each fix is a patch on the last, and every patch is a chance to reintroduce the first bug in a new shape. This is the part nobody tells you about hand-rolled URL matching: it isn't hard because regex is hard. It's hard because "does this path match this shape" has a dozen boundary conditions, and a hand-written pattern only encodes the ones you happened to think of on the day you wrote it. The API built for exactly this job T

本文内容来源于互联网,版权归原作者所有
查看原文