Skip to content

Instantly share code, notes, and snippets.

@steveneaston
Created December 5, 2016 13:36
Show Gist options
  • Save steveneaston/889df854cb204264400af2c8f607492e to your computer and use it in GitHub Desktop.
Save steveneaston/889df854cb204264400af2c8f607492e to your computer and use it in GitHub Desktop.
Javascript Route Generator

Usage

// 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});
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