Fix url url using javascript

I want to parse a hash fragment in an associative array in javascript as being superglobal in $ _GET in PHP. Here is the url:

www.mysite.com/randompage#name=donald&lastname=mclotsoquestions&age=25 

So far I have this:

 var hashfragment = location.hash; var hashfragment_array = hashfragment.split('&'); 

Hashfragment_array is ["# name = donald", "lastname = mclotsoquestions", "age = 25"]

How can I create key value pairs from this?

+3
source share
3 answers

Use jQuery BBQ , which is a cue-tested library that handles state management.

 $(window).on('hashchange', function(e) { // event fired when the fragment changes var frag = $.deparam.fragment(); }); 

It also makes it easy to add or modify a fragment:

 $.bbq.pushState({ someParam: 'value' }); 
+3
source

Use this:

 var hash_array = location.hash.substring(1).split('&'); var hash_key_val = new Array(hash_array.length); for (var i = 0; i < hash_array.length; i++) { hash_key_val[i] = hash_array[i].split('='); } 

Now hash_key_val[index] is an array of two elements, where the first element is the name of the key parameter, and the second is the corresponding value.

Edit:

After some time, having studied this case, I felt that I needed to rewrite it - to return an object instead of an array of arrays. I see that the balafi have done this before, but I cannot bear to make my answer so contradictory and legible. Full example in fiddle . Function source here:

 function getParameters(location) { if (typeof location === 'undefined') { location = window.location; } var hashParams = new (function Params() {})(); if (location.hash.length === 0) { return hashParams; }; var hashArray = location.hash.substring(1).split('&'); for (var i in hashArray) { var keyValPair = hashArray[i].split('='); hashParams[keyValPair[0]] = keyValPair[1]; } return hashParams; } 
+5
source
 var str = www.mysite.com/randompage#name=donald&lastname=mclotsoquestions&age=25 var vars = str.substring(1).split('&'); var key = {}; for (i=0; i<vars.length; i++) { var tmp = vars[i].split('='); key[tmp[0]] = tmp[1]; } // key['name'] = "donald" <-- // key['lastname'] = "mclotsoquestions" <-- // key['age'] = "25" <-- 
+4
source

Source: https://habr.com/ru/post/894972/


All Articles