Skip to content

Instantly share code, notes, and snippets.

@YouriT
Last active December 24, 2020 13:50
Show Gist options
  • Save YouriT/7eac60ee7007d026a7e05dbc9cbebc40 to your computer and use it in GitHub Desktop.
Save YouriT/7eac60ee7007d026a7e05dbc9cbebc40 to your computer and use it in GitHub Desktop.
url.join like function for the browser
function urlJoin(/* components */) {
const components = Array.prototype.slice.call(arguments);
let queryParamsReached = false;
function urlComponentsReducer(accumulator, currentComponent, currentIndex) {
if (currentComponent instanceof Array) {
return accumulator + (queryParamsReached ? '' : '/') + currentComponent.reduce(urlComponentsReducer);
}
let modifiableComponent = currentComponent;
if (!queryParamsReached && currentComponent.indexOf('?') > -1) {
queryParamsReached = true;
}
if (currentComponent[currentComponent.length - 1] === '/') {
modifiableComponent = currentComponent.slice(0, -1);
}
if (currentIndex > 0 && currentComponent[0] !== '/' && !queryParamsReached) {
modifiableComponent = '/' + currentComponent;
} else if (currentIndex === 0 && currentComponent[0] === '/' && currentComponent[1] === '/' && typeof window !== 'undefined' && window.location && window.location.protocol) {
modifiableComponent = window.location.protocol + currentComponent;
}
return accumulator + modifiableComponent;
}
return components.reduce(urlComponentsReducer, '').replace(/[?/]+$/, '');
}
@YouriT
Copy link
Author

YouriT commented Apr 25, 2018

urlJoin('//google.com', '/test/', '?','k=v') // https://google.com/test?k=v
urlJoin('//google.com', '/test/', '?','') // https://google.com/test
urlJoin('//google.com', '/test/', ['go', '/deeper/?']) // https://google.com/test/go/deeper
urlJoin('//google.com', '/test/', ['go', '/deeper/?', 'key=value']) // https://google.com/test/go/deeper/?key=value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment