Reputation: 4564
Example:
www.site.com/index.php#hello
Using jQuery, I want to put the value hello
in a variable:
var type = …
Upvotes: 242
Views: 214385
Reputation: 97727
No need for jQuery
var type = window.location.hash.substr(1);
Since String.prototype.substr
is deprecated use substring
instead.
var type = window.location.hash.substring(1);
Upvotes: 644
Reputation: 1129
Get fragment of current document location
var hash = window.location.hash;
Get fragment from string
// absolute
var url = new URL('https://example.com/path/index.html#hash');
console.log(url.hash);
// relative (second param is required, use any valid URL base)
var url2 = new URL('/path/index.html#hash2', 'http://example');
console.log(url2.hash);
Upvotes: 3
Reputation: 61505
It's very easy. Try the below code
$(document).ready(function(){
var hashValue = location.hash.replace(/^#/, '');
//do something with the value here
});
Upvotes: 8
Reputation: 27525
I had the URL from run time, below gave the correct answer:
let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);
hope this helps
Upvotes: 5
Reputation: 1833
Use the following JavaScript to get the value after hash (#) from a URL. You don't need to use jQuery for that.
var hash = location.hash.substr(1);
I have got this code and tutorial from here - How to get hash value from URL using JavaScript
Upvotes: 8
Reputation: 1561
Based on A.K's code, here is a Helper Function. JS Fiddle Here (http://jsfiddle.net/M5vsL/1/) ...
// Helper Method Defined Here.
(function (helper, $) {
// This is now a utility function to "Get the Document Hash"
helper.getDocumentHash = function (urlString) {
var hashValue = "";
if (urlString.indexOf('#') != -1) {
hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
}
return hashValue;
};
})(this.helper = this.helper || {}, jQuery);
Upvotes: 2
Reputation: 19282
var url ='www.site.com/index.php#hello';
var type = url.split('#');
var hash = '';
if(type.length > 1)
hash = type[1];
alert(hash);
Working demo on jsfiddle
Upvotes: 13
Reputation: 9469
You may do it by using following code:
var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);
Upvotes: 37