How to get the hashtag value and ampersand value of a url in Javascript?

28,095

Solution 1

var hash = window.location.hash;

More info here: https://developer.mozilla.org/en/DOM/window.location

Update: This will grab all characters after the hashtag, including any query strings. From the MOZ manual:

window.location.hash === the part of the URL that follows the # symbol, including the # symbol.
You can listen for the hashchange event to get notified of changes to the hash in
supporting browsers.

Now, if you need to PARSE the query string, which I believe you do, check this out here: How can I get query string values in JavaScript?

Solution 2

To grab the hash:

location.hash.substr(1); //substr removes the leading #

To grab the query string

location.search.substr(1); //substr removes the leading ?

[EDIT - since you seem to have a sort query-string-esq string which is actually part of your hash, the following will retrieve and parse it into an object of name/value pairings.

var params_tmp = location.hash.substr(1).split('&'),
    params = {};
params_tmp.forEach(function(val) {
    var splitter = val.split('=');
    params[splitter[0]] = splitter[1];
});
console.log(params.set); //"none"
Share:
28,095
Mike
Author by

Mike

S...O..aakh

Updated on July 24, 2020

Comments

  • Mike
    Mike almost 4 years

    I have a url like http://www.example.com/folder/file.html#val=90&type="test"&set="none"&value="reset?setvalue=1&setvalue=45"

    Now I need to get the portion of url from starting from #, How do I get that, I tried using window.location.search.substr(); but looks like that searches for ? in a url. is there a method to get the value of url after #

    How do I also get a portion of url from ampersand &

    Thanks, Michael