Search code examples
javascriptjqueryhtmlurlfragment-identifier

How do you read a hash with an "&" sign in the URL?


I am building a dynamic website using jQuery and Ajax. I want to read the id after the hash in the following URL:

something.php#type=abc&id=123

My current code to read hash value is:

var hash = location.hash.substr(1);
alert(hash);

Solution

  • You can do something like this:-

    var hash = window.location.hash.substr(1);
    var searchParams = new URLSearchParams(hash);
    if(searchParams.has('id')) {
      var id = searchParams.get('id');
      console.log(id);
    }
    

    And same for other params if any. Hope this helps.