How to check a URL contains a hash or not using JavaScript?

To check whether a URL contains a hash (#) fragment or not in JavaScript, we can use the window.location.hash property. This property returns the hash portion of the URL, including the # symbol, or an empty string if no hash exists.

What is a URL Hash?

A URL hash is the part of a URL that comes after the # symbol. For example, in the URL https://example.com/page#section1, the hash is #section1. Hashes are commonly used for navigation within a single page or to reference specific sections of content.

Syntax

window.location.hash

This property returns:

  • The hash fragment (including #) if present
  • An empty string if no hash exists

Basic Example

<!DOCTYPE html>
<html>
<head>
    <title>Check URL Hash</title>
</head>
<body>
    <h3>URL Hash Checker</h3>
    
    <p>Current URL: <span id="currentUrl"></span></p>
    <p>Hash Status: <span id="hashStatus"></span></p>
    
    <button onclick="checkHash()">Check Hash</button>
    <br><br>
    <a href="#section1">Add #section1 to URL</a>
    <br>
    <a href="#about">Add #about to URL</a>
    <br>
    <a href="?">Remove hash from URL</a>
    
    <script>
        function checkHash() {
            // Get current URL
            document.getElementById('currentUrl').textContent = window.location.href;
            
            // Check if hash exists
            const hash = window.location.hash;
            const statusElement = document.getElementById('hashStatus');
            
            if (hash) {
                statusElement.innerHTML = '<span style="color: green;">Hash found: ' + hash + '</span>';
            } else {
                statusElement.innerHTML = '<span style="color: red;">No hash found</span>';
            }
        }
        
        // Check hash on page load
        window.onload = checkHash;
        
        // Check hash when URL changes
        window.onhashchange = checkHash;
    </script>
</body>
</html>

Different Methods to Check Hash

Method 1: Simple Boolean Check

function hasHash() {
    return window.location.hash !== '';
}

// Simulate different URLs
console.log('Checking hash presence:');
console.log(hasHash()); // Returns true/false based on current URL

Method 2: Using Length Property

function checkHashLength() {
    const hash = window.location.hash;
    return hash.length > 0;
}

console.log('Hash exists:', checkHashLength());

Method 3: Complete Hash Information

function getHashInfo() {
    const hash = window.location.hash;
    
    return {
        hasHash: hash !== '',
        hashValue: hash,
        hashWithoutSymbol: hash.substring(1) // Remove # symbol
    };
}

// Example output
const hashInfo = getHashInfo();
console.log('Hash Info:', hashInfo);
Hash Info: { hasHash: false, hashValue: '', hashWithoutSymbol: '' }

Practical Use Cases

<!DOCTYPE html>
<html>
<head>
    <title>Hash Navigation Example</title>
    <style>
        .section { margin: 20px 0; padding: 15px; border: 1px solid #ccc; }
        .highlight { background-color: yellow; }
    </style>
</head>
<body>
    <nav>
        <a href="#home">Home</a> |
        <a href="#about">About</a> |
        <a href="#contact">Contact</a>
    </nav>
    
    <div id="home" class="section">
        <h2>Home Section</h2>
        <p>This is the home section.</p>
    </div>
    
    <div id="about" class="section">
        <h2>About Section</h2>
        <p>This is the about section.</p>
    </div>
    
    <div id="contact" class="section">
        <h2>Contact Section</h2>
        <p>This is the contact section.</p>
    </div>
    
    <script>
        function highlightSection() {
            // Remove previous highlights
            const sections = document.querySelectorAll('.section');
            sections.forEach(section => section.classList.remove('highlight'));
            
            // Check if hash exists
            const hash = window.location.hash;
            if (hash) {
                const targetSection = document.querySelector(hash);
                if (targetSection) {
                    targetSection.classList.add('highlight');
                }
            }
        }
        
        // Highlight section on hash change
        window.onhashchange = highlightSection;
        window.onload = highlightSection;
    </script>
</body>
</html>

Key Points

  • window.location.hash returns the hash including the # symbol
  • Returns empty string if no hash exists
  • Hash changes can be detected using the hashchange event
  • Hash values are case-sensitive
  • Useful for single-page application navigation

Conclusion

Checking for URL hashes in JavaScript is straightforward using window.location.hash. This technique is essential for creating interactive single-page applications and implementing smooth navigation between page sections.

Updated on: 2026-03-15T23:19:00+05:30

962 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements