// Single parameter
route('users/{id}', 1);
// Array of parameters
route('users/{user_id}/docs/{doc_id}', [1, 548]);
// Parameter object
route('users/{user_id}/docs/{doc_id}', {user_id: 1, doc_id: 548});
Created
December 5, 2016 13:36
-
-
Save steveneaston/889df854cb204264400af2c8f607492e to your computer and use it in GitHub Desktop.
Javascript Route Generator
This file contains hidden or 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 route(uri, params) { | |
if (typeof params !== 'object') { | |
return route(uri, [params]); | |
} | |
if (Array.isArray(params)) { | |
return uri.replace(/\{(\w+)\}/g, function(s, key) { | |
return params.shift() || key; | |
}); | |
} | |
return uri.replace(/\{(\w+)\}/g, function(s, key) { | |
return params[key] || key; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment