window.location.hash returns hash tag in front of value
Solution 1
There's nothing much to explain. It is the way it works.
Read more here: http://www.w3schools.com/jsref/prop_loc_hash.asp
Definition and Usage
The hash property returns the anchor portion of a URL, including the hash sign (#).
Solution 2
You can change it if you want by simply changing the hash name:
//Your old hash name caught in a variable
var nameHash = location.hash;
//Your new hash name without "#"
var newHashName = nameHash.replace("#","");
Solution 3
var hash = window.location.hash.substring(1);
This omits the first character of the string, which is the hash tag.
Solution 4
You can repalce #
but this way will create conflict and won't work with javascript.
Here is window.location reference link.
Here is different usage examples:
$(document).ready(function () {
var urlHash = window.location.hash;
var sampleURL = '#categoryId=5&manufacturerId=8';
if ( urlHash.length > 1 ) {
//do stuff
}else{
//if value is empty, do stuff
}
if ( urlHash === sampleURL ) {
commonResponse();
}
$('a').click(function() {
var target = $(this).attr('href');
if (target === sampleURL ) {
commonResponse();
}
});
function commonResponse() {
//alert('ok');
}
});
Comments
-
Ivan Stoyanov almost 2 years
I have the following code in MVC3 view:
$(document).ready(function () { if (window.location.hash) { var manager= new Manager(); manager.doSomeStuff(window.location.hash); } });
The interesting thing is that when there is no hash tag in the URL, or there is only a hash tag example:
http://localhost:1223/Index/AboutUs http://localhost:1223/Index/AboutUs#
When the
window.location.hash
is empty and the function is not executed. But when there is some value in the hash tag:http://localhost:1223/Index/AboutUs#categoryId=5&manufacturerId=8
The value in the
window.location.hash
is#categoryId=5&manufacturerId=8
Can you explain to me why the
#
tag is included in the value and why when there is no value after the#
tag, thewindow.location.hash
is empty. -
Ivan Stoyanov over 11 yearsYes, I saw the definition, but it seems somehow strange that the hash sign is returned with the value. That is why I asked the question. Also when you are setting the window.location.hash value, you do not need to add the hash sign to the string.
-
Bernard almost 7 yearsThis might produce undesirable results if the hash contains another
#
character.