How to replace url parameter with javascript/jquery?

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

    2020 answer since I was missing the functionality to automatically delete a parameter, so:

    Based on my favorite answer https://stackoverflow.com/a/20420424/6284674 : I combined it with the ability to:

    • automatically delete an URL param if the value if null or '' based on answer https://stackoverflow.com/a/25214672/6284674

    • optionally push the updated URL directly in the window.location bar

    • IE support since it's only using regex and no URLSearchParams

    JSfiddle: https://jsfiddle.net/MickV/zxc3b47u/

    
    function replaceUrlParam(url, paramName, paramValue){
        if(paramValue == null || paramValue == "")
            return url
            .replace(new RegExp('[?&]' + paramValue + '=[^&#]*(#.*)?$'), '$1')
            .replace(new RegExp('([?&])' + paramValue + '=[^&]*&'), '$1');   
        url = url.replace(/\?$/,'');
        var pattern = new RegExp('\\b('+paramName+'=).*?(&|$)')
        if(url.search(pattern)>=0){
            return url.replace(pattern,'$1' + paramValue + '$2');
        }
        return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
    }
    
    // Orginal URL (default jsfiddle console URL)
    //https://fiddle.jshell.net/_display/?editor_console=true
    
    console.log(replaceUrlParam(window.location.href,'a','2'));   
    //https://fiddle.jshell.net/_display/?editor_console=true&a=2
    
    console.log(replaceUrlParam(window.location.href,'a',''));   
    //https://fiddle.jshell.net/_display/?editor_console=true
    
    console.log(replaceUrlParam(window.location.href,'a',3));   
    //https://fiddle.jshell.net/_display/?editor_console=true&a=3
    
    console.log(replaceUrlParam(window.location.href,'a', null));   
    //https://fiddle.jshell.net/_display/?editor_console=true&
    
    //Optionally also update the replaced URL in the window location bar
    //Note: This does not work in JSfiddle, but it does in a normal browser
    function pushUrl(url){
        window.history.pushState("", "", replaceUrlParam(window.location.href,'a','2'));   
    }
    
    
    pushUrl(replaceUrlParam(window.location.href,'a','2'));   
    //https://fiddle.jshell.net/_display/?editor_console=true&a=2
    
    pushUrl(replaceUrlParam(window.location.href,'a',''));   
    //https://fiddle.jshell.net/_display/?editor_console=true
    
    pushUrl(replaceUrlParam(window.location.href,'a',3));   
    //https://fiddle.jshell.net/_display/?editor_console=true&a=3
    
    pushUrl(replaceUrlParam(window.location.href,'a', null));   
    //https://fiddle.jshell.net/_display/?editor_console=true&
    
    

提交回复
热议问题