skip to Main Content

I have a menu with links that may look like one of the following:

mywebsite.com/#find
mywebsite.com/about-us/#team
mywebsite.com/#social
mywebsite.com/services/#something

I want to do something only to the first and third links (the ones that don’t have a subdirectory in the url path). How do I check if a # hash is the first element after the first slash in the link?

$('#menu a').click(function() {
    
  var target = this.href;

  // check if "/#" is the first thing after the domain name
 
});

Thank you.

2

Answers


  1. Let’s first ignore the https:// part then find the first / and hope to find a # after it.

    var tests = `mywebsite.com/#find
    mywebsite.com/about-us/#team
    https://mywebsite.com/#social
    mywebsite.com/services/#something`.split("n");
    
    function isMyHash(url) {
      var start = url.indexOf("://") > -1 ? url.indexOf("://") + 3 : 0;
      start = url.indexOf("/", start);
      return (url.substring(start + 1, start + 2) == '#')
    
    }
    
    tests.forEach(function(test) {
      console.log(test, isMyHash(test) ? "✔" : "x")
    })
    Login or Signup to reply.
  2. The URL class that parse URLs can help you. URL.pathname property contain path of url (string after domain)

    $('#menu a').click(function(e) {
      if (new URL(this.href).pathname == "/"){
        // Do something
      }
    });
    

    More accurate mode is

    $('#menu a').click(function(e) {
      let url = new URL(this.href)
      if (url.pathname == "/" && url.hash != ''){
        // Do something
      }
    });
    
    $('#menu a').click(function(e) {
      e.preventDefault();
      if (new URL(this.href).pathname == "/")
        console.log("true");
    });
    a {display: block}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="menu">
      <a href="http://mywebsite.com/#find">mywebsite.com/#find</a>
      <a href="http://mywebsite.com/about-us/#team">mywebsite.com/about-us/#team</a>
      <a href="http://mywebsite.com/#social">mywebsite.com/#social</a>
      <a href="http://mywebsite.com/services/#something">mywebsite.com/services/#something</a>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search