Preview:
//Get hash of a given url

var some_url = 'https://usefulangle.com/posts?123#slider'

var hash = new URL(some_url).hash;

// "#slider"
console.log(hash);

//
//
//


//Get hash of the current url

// document.URL refers to the current url
var hash = new URL(document.URL).hash;

console.log(hash);



//
//
//


//Change hash of a given url

var some_url = 'https://usefulangle.com/posts?123#slider'

var url_ob = new URL(some_url);
url_ob.hash = '#reviews';

// new url string
var new_url = url_ob.href;

// "https://usefulangle.com/posts?123#reviews"
console.log(new_url);


//
//
//


//Change hash of the current url

// document.URL is the current url
var url_ob = new URL(document.URL);
url_ob.hash = '#345';

// new url
var new_url = url_ob.href;

// change the current url
document.location.href = new_url;


//
//
//

/*
Detecting Change in Hash of the Current URL

The window.hashchange event can be listened to know when the hash fragment in the current url changes.
*/

window.addEventListener('hashchange', function() {
	// new hash value
	console.log(new URL(document.URL).hash);
});
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter