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
Many times we modify the web page elements depending on the hash (#) value of the current URL. It’s very effective way to pass a value with the URL and load the web page based on that value. Using JavaScript you can easily get the value after the hashtag (#) from the URL, there are no need to use jQuery.
// Get the hash value from the browser URL const hashValue = window .location.hash; console .log (hashValue); // #portfolio The property returns the hash value with the hash symbol as its prefix. See the above code live in this codesandbox.
Using JavaScript you can easily get the value after the hashtag (#) from the URL, there are no need to use jQuery. Also, you can get the hash value from href using simple JavaScript code. The following JavaScript code will show how to get value with, after and before hashtag (#). var hash = location.hash;
The URLSearchParams is an interface used to provide methods that can be used to work with an URL. The URL string is first separated to get only the parameters portion of the URL. The split () method is used on the given URL with the “?” separator. It will separate the string into 2 parts.
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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With