Example:
www.site.com/index.php#hello
Using jQuery, I want to put the value hello
in a variable:
var type = …
Example:
www.site.com/index.php#hello
Using jQuery, I want to put the value hello
in a variable:
var type = …
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);
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);
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
It's very easy. Try the below code
$(document).ready(function(){
var hashValue = location.hash.replace(/^#/, '');
//do something with the value here
});
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
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
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);
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);