Last active
March 14, 2022 08:04
-
-
Save MrSwed/9164b1ffad0dfe33efdb3ca11b7377eb to your computer and use it in GitHub Desktop.
Short unparam string or object attr
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
/* | |
* Unparam url link parameters string 'key1=value1&key2=value2' to object {key1: 'value1', key2: 'value2'} | |
* https://gist.github.com/MrSwed/9164b1ffad0dfe33efdb3ca11b7377eb | |
* Usage: | |
* $("a").unparam() // return params from href {param1:"value1","param2":"value2"} | |
* $("div").unparam({"attr":"data-url"}) // return params from url at attr 'data-url' {param1:"value1","param2":"value2"} | |
* $("div").unparam("key1=value1&key2=value2"}) // return params from url at attr 'data-url' {param1:"value1","param2":"value2"} | |
* $.fn.unparam({"data":"key1=value1&key2=value2"}) // return {key1: 'value1', key2: 'value2'} | |
*/ | |
$.extend({ | |
"unparam": function(args){ | |
var t = this, data; | |
args = $.extend({'attr': 'href'}, typeof args === "string" ? {data: args} : args); | |
data = args["data"] ?? $(t).filter("[" + args["attr"] + "]").attr(args["attr"]); | |
if (/\?/.test(data)) data = data.split("?", 2)[1]; | |
return data?.split("&")?.reduce((s, i) => { | |
i = i.split("="); | |
s[i[0]] = i[1] ?? null; | |
return s; | |
}, {}) | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment