How to get #hash value in a URL in JS

前端 未结 6 1968
小蘑菇
小蘑菇 2020-12-14 18:38

For example, I have a URL as :

http://www.google.com/#hash=value2x

I want a js code to return just value2x. I tried

相关标签:
6条回答
  • 2020-12-14 19:08

    If you are doing extensive url manipulations, then you shoud check out JQuery URL plugin.

    To access the params in url hashes

        $.url('http://www.google.com/#hfh=fdg&hash=value2x').fparam('hash');
    

    or if its current url

        $.url().fparam('hash');
    

    Hope it helps

    0 讨论(0)
  • 2020-12-14 19:12

    How about

    location.hash.split('hash=')[1].split('&')[0]
    

    This will split the hash at hash= and take the value after hash= and before any other argument .

    0 讨论(0)
  • 2020-12-14 19:13
    function getHashValue(key) {
      var matches = location.hash.match(new RegExp(key+'=([^&]*)'));
      return matches ? matches[1] : null;
    }
    
    // usage
    var hash = getHashValue('hash');
    
    0 讨论(0)
  • 2020-12-14 19:16

    The URLSearchParams class can be reused for this purpose.

    var urlParams = new URLSearchParams(window.location.hash.replace("#","?"));
    var hash = urlParams.get('hash');
    
    0 讨论(0)
  • 2020-12-14 19:16
    location.parseHash = function(){
       var hash = (this.hash ||'').replace(/^#/,'').split('&'),
           parsed = {};
    
       for(var i =0,el;i<hash.length; i++ ){
            el=hash[i].split('=')
            parsed[el[0]] = el[1];
       }
       return parsed;
    };
    
    var obj= location.parseHash();
        obj.hash;  //fdg 
        obj.hfh;   //value2x
    
    0 讨论(0)
  • 2020-12-14 19:33

    Split on & and then on =:

    pairs = location.hash.substr(1).split('&').map(function(pair) {
        var kv = pair.split('=', 2);
        return [decodeURIComponent(kv[0]), kv.length === 2 ? decodeURIComponent(kv[1]) : null];
    })
    

    Here pairs will be an array of arrays with the key at 0 and the value at 1:

    [["hfh","fdg"],["hash","value2x"]]
    
    0 讨论(0)
提交回复
热议问题