Skip to content

Instantly share code, notes, and snippets.

@johnsmith17th
Created April 16, 2013 01:26
Show Gist options
  • Save johnsmith17th/5392656 to your computer and use it in GitHub Desktop.
Save johnsmith17th/5392656 to your computer and use it in GitHub Desktop.
Work around with url with params. for routing. Found in node-restify.
/**
* Returns a string representation of a URL pattern ,
* with its parameters filled in by the passed hash.
*
* If a key is not found in the hash for a param, it is left alone.
*
* @param {Object} a hash of parameter names to values for substitution.
*/
function realizeUrl(pattern, params) {
var p = pattern.replace(/\/:([^/]+)/g, function (match, k) {
return (params.hasOwnProperty(k) ? '/' + params[k] : match);
});
// return (require('./utils').sanitizePath(p));
// cleans up sloppy URL paths, like /foo////bar/// to /foo/bar.
// ** copy from sanitizePath() **
// be nice like apache and strip out any //my//foo//bar///blah
p = p.replace(/\/\/+/g, '/');
// kill a trailing '/'
if (p.lastIndexOf('/') === (p.length - 1) && p.length > 1)
p = p.substr(0, p.length - 1);
return (p);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment