I have code for get part of anchor:
function _get_part(queryString, name) {
var match = '&' + name + '=';
var i = queryString.indexOf(match);
if(i < 0) {
match = name + '=';
if(queryString.slice(0, match.length) == match)
i = 0;
}
if(i > -1) {
i += match.length;
return queryString.slice(i, queryString.indexOf('&', i) >>> 0);
}
};
function get_location_hash() {
return window.location.hash.substr(2);
}
function get_part(name) {
return _get_part(get_location_hash(), name);
}
I need a function for changing a part of the anchor, if this part exists, or add a part if it does not exist.
At this time I use the following code:
function set_part(queryString, key, value) {
var oldv = key + '=' + get_part(key);
var newv = key + '=' + value;
window.location.hash = '/' + queryString.replace(oldv, newv);
}
But if the part of the anchor does not exist, the anchor doesn’t change.
URL format: …page/#/var1=blablabla&var2=var2text&gghh=edere
Anchor – #/var1=blablabla&var2=var2text&gghh=edere
Sorry about my English.
Thanks a lot!
update:
it awesome, thank you very much!
only one problem: i load page withoud any anchors:
…/page/
nex use this code:
set_part(get_location_hash(), 'filter', 'data');
set_part(get_location_hash(), 'filter2', 'data2');
set_part(get_location_hash(), 'fdgfg', 'fdgfdg');
alert(get_part('fdgfg'));
and receive …/page/#/=&filter=data&filter2=data2&fdgfg=fdgfdg
how to delete first ‘=’ symbol?
Your functions work correctly if the
keyis already present in the url hash.For example, if your url is:
Then, calling
set_part()like this:will change the hash as follows:
Notice: it changed the value of
var2properly. But it did add an extra slash at the beginning.The problem is that it won’t add the parameter, if no such key previously existed. If you want to do this, then I’d recommend something like the following:
Now, if the url of your page is
and you call it like this:
then you can see that both forms work correctly.
You can see this example in action at jsfiddle.