node package manager
Don’t reinvent the wheel. Reuse code within your team. Create a free org »

path-to-url

Path-to-URL

npm Travis Code Climate Code Climate Coverage Gemnasium

Turns an Express-style path string such as /user/:name into a URL like /user/brentburgoyne to support reverse routing.

Installation

$ npm install path-to-url --save

Usage

var pathToUrl = require('path-to-url');
 
// pathToUrl(path, params) 
  • path A string in the express path format.
  • params An object where the keys match named params in the path to be replaced with the value.
    • params.param The value that will replace :param in the URL.
    • params.$ Special key where the value replaces the * wildcard in greedy paths.

Simple

pathToUrl('/user/:name', { name: 'brentburgoyne' });
// => "/user/brentburgoyne" 

Optional params

pathToUrl('/results/:page?', {});
// => "/results" 
 
pathToUrl('/results/:page?', { page: 47 });
// => "/results/47" 

Suffixes

pathToUrl('/results.:format?', {});
// => "/results" 
 
pathToUrl('/results.:format?', { format: 'json' });
// => "/results.json" 

Wildcard

pathToUrl('/results*', {});
// => "/results" 
 
pathToUrl('/results*', { $: '/anthing/goes/here' });
// => "/results/anything/goes/here" 

Disclaimer

While the most common use cases are covered, this module is not currently able to support every path supported by Express. Some of the things tat are not supported include optional groups and custom regular expressions.