Friday, February 23, 2018

Make a JavaScript array from URL




I need to make a Javascript array from URL, eg:



turn this:



http://maps.google.com/maps/api/staticmap?center=Baker Street 221b, London&size=450x450&markers=Baker Street 221b, London&sensor=false


Into something like:




array['center'] = Baker Street 221b, London
array['size'] = 450x450
// and so on...


I need to make this serializaion/unserialization work both ways (url to array and array to the part of the url). Are there some built-in functions that do this?



Thanks in advance!


Answer



URL to array: (adapted from my answer here)




function URLToArray(url) {
var request = {};
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
if(!pairs[i])
continue;
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}

return request;
}


Array to URL:



function ArrayToURL(array) {
var pairs = [];
for (var key in array)
if (array.hasOwnProperty(key))


pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(array[key]));
return pairs.join('&');
}

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...