getParams function
A function to get all the parameters in a url, and return them as an object.
by Ali Wright
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<div id="output"></div>
JavaScript
function getParams( url ) {
// extra code here for testing purposes
// normally you wouldn't pass a url parameter in
// this is just to simulate a typical url
var ampersand = "&";
if(_.isUndefined(url)) {
url = location.search;
ampersand = "&";
}
// the Underscore/JS magic...
// return _.chain(location.search.slice(1).split('&')) // < original code
return _.chain(url.slice(1).split( ampersand ))
.map(function (item) { if (item) { return item.split('='); } })
.compact()
.object()
.value();
}
var testUrl = "?email=someone@example.com&subject=hello",
urlObject = getParams( testUrl );
if(_.isObject( urlObject )) {
var str = JSON.stringify(urlObject, null, 4);
$('#output').html( str );
}