If I am on https://www.website.com/#something
, how can I return the hash value "something"
from the URL?
4 Answers
window.location.hash
its that simple.
donot use all those methods which consume CPU and effects performance.
If DOM provides something predefined use it first.
To pass value to PHP please do and ajax call to php.
var hash = window.location.hash;
$.ajax({
url: 'someurl.php',
data: {hash: hash},
success: function(){}
})
-
I knew how to do an ajax call, but that's the only way?– user1661548Commented Apr 1, 2013 at 10:18
-
ya thats the only way to access a server-side language from browser AFAIK.– SandeepCommented Apr 1, 2013 at 11:26
You can use the location.hash property to grab the hash of the current page:
var hash = window.location.hash;
update
As there is a built in method to get the hash via DOM above answer is not appropriate
var hashTag = window.location.hash
alert(hashTag);
will do the magic.
Old answer
You can do something as below if you have multiple hashes in your url
//var href = location.href; // get the url in real worl scenario
var href = "www.bla.com#myhashtag"; // example url
var split = href.split("#"); // split the string; usually there'll be only one # in an url so there'll be only two parts after the splitting
var afterSplit = "Error parsing url";
if(split[1] != null){
afterSplit = split[1];
}
// If everything went well shows split[1], if not then de default error message is shown
alert(afterSplit);
Here is an example Live Fiddle
-
DOM already provides u a predefined variable location.hash then its waste of using this method– SandeepCommented Apr 1, 2013 at 10:09
-
2I didn't down vote, but that's way more complicated than it needs to be. Commented Apr 1, 2013 at 10:10
-
-
1Weird voting on this question. The correct answer gets two downvotes, while the convoluted answer, later changed to copy the correct answer gets two upvotes.– gilly3Commented Apr 1, 2013 at 18:25
You could use this
h=new URL(location).hash.split`&`.find(e=>/hash_name/.test(e)).split`=`[1]
window.location.hash
its gives u the hash