How to replace url parameter with javascript/jquery?

前端 未结 17 2329
旧时难觅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:27

    Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:

    /search?searchquery=text and 'query' is provided.
    

    In this case searchquery param value is changed.

    Code:

    function replaceUrlParam(url, paramName, paramValue){
        var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
        var newUrl=url
        if(url.search(pattern)>=0){
            newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
        }
        else{
            newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
        }
        return newUrl
    }
    

提交回复
热议问题