ts-prime
Version:
A utility library for JavaScript and Typescript.
74 lines (73 loc) • 2.53 kB
JavaScript
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
/**
* Converts url to relative url
* @param url - Valid url
* @category Utility
*/
export function urlToRelative(url) {
return url.replace(/^[^/]+\/\/[^/]+/, '');
}
/**
* Joins two url paths
* @param url - Valid url
* @category Utility
*/
export function urlJoin() {
var concat = [];
for (var _i = 0; _i < arguments.length; _i++) {
concat[_i] = arguments[_i];
}
var resultArray = [];
var strArray = __spreadArrays(concat);
if (strArray.length === 0) {
return '';
}
if (typeof strArray[0] !== 'string') {
throw new TypeError('Url must be a string. Received ' + strArray[0]);
}
if (strArray[0].match(/^[^/:]+:\/*$/) && strArray.length > 1) {
var first = strArray.shift();
strArray[0] = first + strArray[0];
}
// There must be two or three slashes in the file protocol, two slashes in anything else.
if (strArray[0].match(/^file:\/\/\//)) {
strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, '$1:///');
}
else {
strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, '$1://');
}
for (var i = 0; i < strArray.length; i++) {
var component = strArray[i];
if (typeof component !== 'string') {
throw new TypeError('Url must be a string. Received ' + component);
}
if (component === '') {
continue;
}
if (i > 0) {
// Removing the starting slashes for each component but the first.
component = component.replace(/^[\/]+/, '');
}
if (i < strArray.length - 1) {
// Removing the ending slashes for each component but the last.
component = component.replace(/[\/]+$/, '');
}
else {
// For the last component we will combine multiple slashes to a single one.
component = component.replace(/[\/]+$/, '/');
}
resultArray.push(component);
}
var str = resultArray.join('/');
str = str.replace(/\/(\?|&|#[^!])/g, '$1');
// replace ? in parameters with &
var parts = str.split('?');
str = parts.shift() + (parts.length > 0 ? '?' : '') + parts.join('&');
return str;
}