Last active
June 25, 2019 13:18
-
-
Save long-lazuli/82e22d56037faf75eff52e2feb35c21a to your computer and use it in GitHub Desktop.
URL utilities using HTML Anchor Element functionalities
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
export default const UrlParser = ( urlStr ) => { | |
const $anchor = document.createElement('a') | |
$anchor.href = urlStr || window.location | |
return { | |
...Object.keys($anchor.__proto__).reduce( | |
(acc, prop) => ({ ...acc, [prop]: $anchor[prop] }), | |
{} | |
), | |
get filename() { return ($anchor.pathname.indexOf('/') > -1) ? $anchor.pathname.split('/').slice(-1)[0] : '' }, | |
get extension() { return (this.filename.indexOf('.') > -1) ? this.filename.split('.').slice(-1)[0] : '' }, | |
setHostname(newHostname){ | |
$anchor.href = $anchor.protocol + newHostname + $anchor.pathname + $anchor.search + $anchor.hash | |
}, | |
setPathname(newPathname){ | |
$anchor.href = $anchor.origin + newPathname + $anchor.search + $anchor.hash | |
}, | |
get parameters() { return _searchStringToObject($anchor.search) }, | |
setParameters(newParameters) { | |
$anchor.href = $anchor.origin + $anchor.pathname + _objectToSearchString(newParameters, '?') + $anchor.hash | |
}, | |
updateParameters(newParameters) { | |
this.setParameters({...this.parameters, ...newParameters}) | |
}, | |
get hashParameters() { return _searchStringToObject($anchor.hash) }, | |
setHashParameters(newHashParameters) { | |
$anchor.href = $anchor.origin + $anchor.pathname + $anchor.search + _objectToSearchString(newHashParameters, '#') | |
}, | |
updateHashParameters(newHashParameters) { | |
this.setHashParameters({...this.hashParameters, ...newHashParameters}) | |
}, | |
toString() { return $anchor.toString() } | |
} | |
} | |
function _searchStringToObject(searchQuery) { | |
const query = ( ['?', '#'].includes(searchQuery[0]) ) ? searchQuery.substring(1) : searchQuery | |
if( query !== '' ) try { return JSON.parse( | |
'{"' + query.replace(/&/g, '","').replace(/=/g,'":"') + '"}', | |
(key, value) => (key === "") ? value : decodeURIComponent(value) | |
) } catch (e) {} | |
return {} | |
} | |
function _objectToSearchString(obj, startChar='') { | |
return Object.keys(obj).reduce( | |
([str, i], key) => obj[key] !== null | |
? [str + `${ i?'&':startChar }${ key }=${ obj[key] }`, ++i] | |
: [str, i], | |
['', 0] | |
)[0] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment