Last active
December 24, 2020 13:50
-
-
Save YouriT/7eac60ee7007d026a7e05dbc9cbebc40 to your computer and use it in GitHub Desktop.
url.join like function for the browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(/[?/]+$/, ''); | |
} |
Author
YouriT
commented
Apr 25, 2018
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment