URL Toolkit
Lightweight library to build an absolute URL from a base URL and a relative URL, written from the spec (RFC 1808). Initially part of HLS.JS.
Methods
buildAbsoluteURL(baseURL, relativeURL, opts={})
Build an absolute URL from a relative and base one.
URLToolkit.buildAbsoluteURL('http://a.com/b/cd', 'e/f/../g');
If you want to ensure that the URL is treated as a relative one you should prefix it with ./
.
URLToolkit.buildAbsoluteURL('http://a.com/b/cd', 'a:b');
URLToolkit.buildAbsoluteURL('http://a.com/b/cd', './a:b');
By default the paths will not be normalized unless necessary, according to the spec. However you can ensure paths are always normalized by setting the opts.alwaysNormalize
option to true
.
URLToolkit.buildAbsoluteURL('http://a.com/b/cd', '/e/f/../g');
URLToolkit.buildAbsoluteURL('http://a.com/b/cd', '/e/f/../g', {
alwaysNormalize: true,
});
normalizePath(url)
Normalizes a path.
URLToolkit.normalizePath('a/b/../c');
parseURL(url)
Parse a URL into its separate components.
URLToolkit.parseURL('http://a/b/c/d;p?q#f');
buildURLFromParts(parts)
Puts all the parts from parseURL()
back together into a string.
Example
var URLToolkit = require('url-toolkit');
var url = URLToolkit.buildAbsoluteURL(
'https://a.com/b/cd/e.m3u8?test=1#something',
'../z.ts?abc=1#test'
);
console.log(url);
Browser
This can also be used in the browser thanks to jsDelivr:
<head>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/url-toolkit@2"
></script>
<script type="text/javascript">
var url = URLToolkit.buildAbsoluteURL(
'https://a.com/b/cd/e.m3u8?test=1#something',
'../z.ts?abc=1#test'
);
console.log(url);
</script>
</head>