How to replace url parameter with javascript/jquery?

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

    In addition to @stenix, this worked perfectly to me

     url =  window.location.href;
        paramName = 'myparam';
            paramValue = $(this).val();
            var pattern = new RegExp('('+paramName+'=).*?(&|$)') 
            var newUrl = url.replace(pattern,'$1' + paramValue + '$2');
            var n=url.indexOf(paramName);
            alert(n)
            if(n == -1){
                newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
            }
            window.location.href = newUrl;
    

    Here no need to save the "url" variable, just replace in current url

提交回复
热议问题