Last active
August 8, 2018 17:24
-
-
Save Bludwarf/47e30652b99dc38328ecaccca0bd8649 to your computer and use it in GitHub Desktop.
Everyday JavaScript utilities
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
var UrlUtils = {}; | |
/** | |
* @param url? par défaut on prend l'URL actuelle | |
* @returns la liste des paramètres dans l'URL (URL décodé) | |
*/ | |
UrlUtils.getParams = function(url) { | |
var result = {}; | |
var search; | |
if (url) { | |
var i = url.indexOf('?'); | |
if (i === -1) return result; | |
search = url.substring(i); | |
} | |
else { | |
search = window.location.search; | |
} | |
if (search) { | |
search.substr(1) // après '?' | |
.split("&") | |
.forEach(function (item) { | |
var tmp = item.split("="); | |
var key = decodeURIComponent(tmp[0]); | |
var val = decodeURIComponent(tmp[1]); | |
result[key] = val; | |
}); | |
} | |
return result; | |
} | |
/** | |
* Alternative à getParams(url) sans parsing complet des paramètres | |
* @author http://stackoverflow.com/a/901144 | |
*/ | |
UrlUtils.getParameterByName = function(name, url) { | |
if (!url) { | |
url = window.location.href; | |
} | |
name = name.replace(/[\[\]]/g, "\\$&"); | |
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), | |
results = regex.exec(url); | |
if (!results) return null; | |
if (!results[2]) return ''; | |
return decodeURIComponent(results[2].replace(/\+/g, " ")); | |
} | |
/** @author http://stackoverflow.com/a/111545/1655155 */ | |
UrlUtils.encodeQueryData = function(data) { | |
var ret = []; | |
for (var d in data) | |
ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d])); | |
return ret.join("&"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment