URL and path utilities.
Usage
var urlUtils = require('url-utils')
, api = '/api/v1/locations'
, id = '12345'
, url = urlUtils.join(api, 'id', id);
console.log(url); //=> /api/v1/locations/id/12345
API
join(...segments): Safely combine path segments
. Segments can be strings, an array of strings, or a mixture of the two.
urlUtils.join('foo', 'bar', 'bat'); //=> foo/bar/bat
urlUtils.join('/foo/', 'bar'); //=> /foo/bar
urlUtils.join(['foo/bar', 'bat'], '/baz'); //=> foo/bar/bat/baz
query(url, query): Safely combine url and queries. Queries are added in alphabetical order
urlUtils.query('foo', {a:'b', b:'c'}); //=> foo&a=b?b=c
urlUtils.query('/foo/', {a:'b'}); //=> /foo&a=b
sanitize(url): Remove trailing '/' and replace double occurence of '/' with single in url
.
urlUtils.sanitize('/api/v1/locations/'); //=> /api/v1/locations
decode(url): Decode escaped url
. Throws error on malformed string.
urlUtils.decode('s%C3%B8k'); //=> søk
urlUtils.decode('\uDFFF'); //=> Error
encode(url): Encode special characters in url
with UTF-8 encoding. Returns url if url is already encoded. Throws error on invalid characters.
urlUtils.encode('foo/søk'); //=> foo/s%C3%B8k
urlUtils.encode('foo/s%C3%B8k?q=bar') //=> foo/s%C3%B8k?q=bar
urlUtils.decode('s%Z3%B8k'); //=> Error
getCurrent(): Retieve the current decoded browser url (including search query strings).
urlUtils.getCurrent(); //=> https://github.com/yr/url-utils
template(str, data, options): Substitute 'data' values in 'str' template, with loose option to return partially replaced string
urlUtils.template('hello {foo}', { foo: 'bar' }); //=> hello bar
urlUtils.template('/{foo}//{bar}/{bat}/', { foo: 'foo', bar: 'bar' }); //=> /foo/bar
urlUtils.template('/{foo}//{bar}/{bat}/', { foo: 'foo', bar: 'bar' }, { loose: true }); //=> /foo/bar/{bat}