v135 · javascript
URL route matcher
Path templates like /users/:id/posts/:slug are ubiquitous in routing libraries. Building them safely requires escaping the literal segments with RegExp.escape() so a path like /api/v1.0/users doesn't turn into a regex bomb where . matches anything.
RegExp.escape: checking…
Route templates
Test URLs
Match results
params extracted from matched segment
| URL | Matched route | Params |
|---|
Generated regexes
RegExp.escape() applied to literal segments
| Template | Compiled regex |
|---|
// Building a path matcher with RegExp.escape
function compileRoute(template) {
// Split on :param tokens
const parts = template.split(/(:[\w]+)/g);
const paramNames = [];
const pattern = parts.map(part => {
if (part.startsWith(':')) {
paramNames.push(part.slice(1));
return '([^/]+)'; // capture group for the param
}
return RegExp.escape(part); // literal segment — dots, slashes, etc. are safe
}).join('');
return { re: new RegExp('^' + pattern + '$'), paramNames };
}
// Without RegExp.escape, /api/v1.0/users matches /api/v1X0/users too
// because '.' is unescaped. With it, only the literal dot matches.