Last active
March 2, 2017 15:17
-
-
Save ztrehagem/5a623ba4dc2153b42725c2f111da07cb to your computer and use it in GitHub Desktop.
rest uri parser / matcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function parse(route, pathname) { | |
var keys = []; | |
var regexpstr = route.split('/').map(function(part) { | |
if (part.startsWith(':')) { | |
keys.push(part.substring(1)); | |
return '([^/]+)'; | |
} else { | |
return escape(part); | |
} | |
}).join(escape('/')); | |
var matches = pathname.match(new RegExp('^' + regexpstr + '$')); | |
if (!matches) return false; | |
matches.shift(); | |
return keys.reduce(function(params, key) { | |
params[key] = matches.shift(); | |
return params; | |
}, {}); | |
} | |
function escape(str) { | |
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); | |
} | |
parse('/users/:id/posts', '/users/123/posts'); | |
//=> { id: '123' } | |
parse('/users/:user_id/posts/:post_id', '/users/123/posts/456'); | |
//=> { user_id: '123', post_id: '456' } | |
parse('/foo/bar/baz', '/foo/bar/baz'); | |
//=> {} | |
parse('/foo/bar/baz', '/hoge/fuga/piyo'); | |
//=> false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment