How to replace url parameter with javascript/jquery?

前端 未结 17 2353
旧时难觅i
旧时难觅i 2020-11-28 04:06

I\'ve been looking for an efficient way to do this but haven\'t been able to find it, basically what I need is that given this url for example:

http://localh         


        
17条回答
  •  借酒劲吻你
    2020-11-28 04:38

    I have get best solution to replace the URL parameter.

    Following function will replace room value to 3 in the following URL.

    http://example.com/property/?min=50000&max=60000&room=1&property_type=House

    var newurl = replaceUrlParam('room','3');
    history.pushState(null, null, newurl);
    

    function replaceUrlParam(paramName, paramValue){
        var url = window.location.href;
    
        if (paramValue == null) {
            paramValue = '';
        }
    
        var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
        if (url.search(pattern)>=0) {
            return url.replace(pattern,'$1' + paramValue + '$2');
        }
    
        url = url.replace(/[?#]$/,'');
        return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
    }
    

    Output

    http://example.com/property/?min=50000&max=60000&room=3&property_type=House

提交回复
热议问题