Created
December 19, 2022 09:23
-
-
Save jkohlin/d9b32e231c260f4a2895d9bbd3a00aa2 to your computer and use it in GitHub Desktop.
Return all search params from a url
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
/** | |
* Description Plockar ut URL-parametrar som ett objekt plus andra godsaker. | |
* @param {string} href | |
* @returns {Object} {...allParams, href:getterFunction, baseUrl:URL, params:URLSearchParams} | |
*/ | |
function getParams(href) { | |
const baseUrl = new URL(href) | |
var paramSeparator = baseUrl.hash.startsWith('#') ? '#' : '?' | |
var params = baseUrl.hash.startsWith('#') ? new URLSearchParams(baseUrl.hash.slice(1)) : new URLSearchParams(baseUrl.search) | |
const obj = { baseUrl, get href() { return this.baseUrl.origin + this.baseUrl.pathname + paramSeparator + this.params.toString() }, params } | |
for (const [key, value] of params.entries()) { | |
obj[key] = value; | |
} | |
params.href = () => this.origin + this.pathname + '#' | |
return obj | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment