Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including path-to-url with all npm packages installed. Try it out:

var pathToUrl = require("path-to-url")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

path-to-url v0.1.0

Turn an Express-style path string such as /user/:name into a 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.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free