JavaScript kullanarak bir URL'de #hash olup olmadığını nasıl kontrol edebilirsiniz?

Yalnızca URL'de bir karma (#) bağlantı olduğunda çalıştırmak istediğim bazı jQuery/JavaScript kodlarım var. JavaScript kullanarak bu karakteri nasıl kontrol edebilirsiniz? Bu gibi URL'leri tespit edebilecek basit bir teste ihtiyacım var:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

Temel olarak şöyle bir şey:

if (thereIsAHashInTheUrl) {        
    do this;
} else {
    do this;
}

Beni doğru yöne yönlendirebilecek biri varsa çok memnun olurum.

Çözüm

Çok basit:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
Yorumlar (11)

Şunları koyun:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>
Yorumlar (1)

Bunu denediniz mi?

if (url.indexOf('#') !== -1) {
    // Url bir # içerir
}

(Burada url kontrol etmek istediğiniz URL'dir, tabii ki).

Yorumlar (0)