relateurl

Create a relative URL with minify options.
With http://domain.com/seg1/seg1-1/ as a base URL, you can produce:
| Before | After |
|---|---|
http://domain.com/seg1/seg1-2/index.html |
../seg1-2/ |
http://domain.com/seg2/seg2-1/ |
/seg2/seg2-1/ |
http://domain.com/seg1/seg1-1/ |
|
httpS://domain.com/seg1/seg1-1/ |
https://domain.com/seg1/seg1-1/ |
../../../../../../../../#anchor |
/#anchor |
Installation
Node.js >= 8 is required. To install, type this at the command line:
npm install relateurl
Usage
Inputs must be URL instances.
const relateURL = require('relateurl');
const base = new URL('http://domain.com/seg1/seg1-1/');
const url = new URL('//domain.com/seg1/seg1-2/index.html', base);
relateURL(url, base, options);
//-> ../seg1-2/
Options
It is simplest to use an option profile, but custom configurations are still possible.
output
Type: Symbol
Default value: relateURL.SHORTEST
The limit of how far the resulting URL should be related. Possible values:
PROTOCOL_RELATIVE: will try to produce something like//domain.com/path/to/file.html.ROOT_PATH_RELATIVE: will try to produce something like/child-of-root/etc/.PATH_RELATIVE: will try to produce something like../child-of-parent/etc/.SHORTEST: will try to choose whichever is shortest betweenPATH_RELATIVEandROOT_PATH_RELATIVE.
Minify Options
Any other defined option will be passed to minurl. Avoid setting stringify to false, as it will prevent any operations performed by this library from being outputted.
Ignoring Basic Authentication
Ignoring a URL's username and password attributes will need the not-so-obvious removeAuth option (from minurl):
const base = new URL('http://user:pass@domain.com/seg1/seg1-1/');
const url = new URL('http://domain.com/seg1/seg1-2/');
relateURL(url, base, {
removeAuth: true
});
//-> ../seg1-2/
Option Profiles
There're two profiles: CAREFUL_PROFILE and COMMON_PROFILE.