TypeScript: How to Get/Set the Hash Segment of a URL

Updated: February 14, 2024 By: Guest Contributor Post a comment

Overview

In the vast ecosystem of web development, URLs play a crucial role in navigating between pages and sections. Among the different parts of a URL, the hash segment, often denoted by a “#” symbol, is commonly used for direct access to specific sections within a webpage. In this tutorial, we delve into the mechanics of manipulating the hash segment of a URL using TypeScript, a powerful superset of JavaScript that adds type safety to the mix.

Understanding the URL Hash Segment

The hash segment in a URL follows the “#” symbol and is used primarily for navigating to specific parts of a web page without reloading the page. This feature is extensively used in single-page applications (SPAs) for routing purposes.

Accessing the Hash in TypeScript

Accessing the hash segment of a URL in TypeScript can be achieved using the window.location.hash property. Here’s a simple example:

const urlHash = window.location.hash;
console.log(urlHash); // Outputs: #sectionName

Setting the Hash Segment

Setting or modifying the hash segment of a URL can also be done via the window.location.hash property in TypeScript. Here’s how you can set a new hash:

window.location.hash = 'newSection';

Upon setting the hash, the browser will navigate to the specified section within the page, without reloading the entire page.

Advanced Manipulation of the URL Hash

While direct assignment works for simple scenarios, more complex situations may require programmatic manipulation of the hash. Let’s explore some techniques.

Listening for Hash Changes

To respond dynamically to changes in the hash segment, you can listen to the window.onhashchange event. This event triggers whenever the hash segment of the URL changes. Here’s an example set up:

window.addEventListener('hashchange', () => {
    console.log('Hash changed!', window.location.hash);
});

Modifying Hash Without Page Scroll

Sometimes, you may want to modify the hash without causing the browser to scroll to the section. This can be achieved using the History API. Here’s how you can replace the current hash without affecting the scroll position:

history.pushState(null, '', '#newHashWithoutScroll');

This method updates the URL’s hash while keeping the page’s current scroll position intact.

Dealing with Complex Hash Values

Dealing with complex hash values or needing to parse hash parameters can involve additional logic. Here’s a method to parse hash parameters into a JavaScript object:

function parseHashParams(hash: string): Record<string, string> {
 let parameters = {};
 hash.replace(/^#?/, '').split('&').forEach((param) => {
  let [key, value] = param.split('=');
  parameters[key] = decodeURIComponent(value || '');
 });
 return parameters;
}

This utility function strips the hash symbol, splits the parameters, and decodes them into a key-value collection, making it easier to work with complex hashes.

Conclusion

Managing the hash segment of a URL in TypeScript offers a myriad of possibilities in improving user navigation and the overall user experience of web applications. Whether you’re working on routing in SPAs, implementing sophisticated in-page navigation, or managing state via the URL, TypeScript coupled with the DOM’s native capabilities makes these tasks intuitive and efficient. As you explore further, you’ll discover even more ways to leverage these techniques to enhance your web applications.