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

后端 未结 9 732
逝去的感伤
逝去的感伤 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:05

    @freedev answer is great, but if you need something very simple (to insert key=value pair to the url and assume that key doesn't already exist), there's a much faster way to do it:

    var addSearchParam = function(url,keyEqualsValue) {
    
        var parts=url.split('#');
        parts[0]=parts[0]+(( parts[0].indexOf('?') !== -1) ? '&' : '?')+keyEqualsValue;
        return parts.join('#');
    
    }
    

    Example usage: addSearchParam('http://localhost?a=1#hash','b=5');

提交回复
热议问题