How to add parameters to a URL that already contains other parameters and maybe an anchor

后端 未结 9 754
逝去的感伤
逝去的感伤 2020-12-05 19:36

I\'m wondering how I can add a new parameter to an existing url. The problem is: the url may also contain an anchor.

For example:

http://www.example         


        
9条回答
  •  旧巷少年郎
    2020-12-05 20:11

    Try this:

    location.href = location.href.replace(location.hash, '') + '&x=y' + location.hash
    

    Update

    What about this:

    var a = document.createElement('a');
    a.href = "http://www.example.com?foo=bar#hashme";
    
    var url = a.href.replace(a.hash, '') + '&x=y' + a.hash;
    

    I found out that the location object can be created by an anchor element(from Creating a new Location object in javascript).

提交回复
热议问题