Remove URL parameters without refreshing page

前端 未结 13 968
执念已碎
执念已碎 2020-12-07 08:00

I am trying to remove everything after the \"?\" in the browser url on document ready.

Here is what I am trying:

jQuery(document).ready(function($)          


        
13条回答
  •  春和景丽
    2020-12-07 08:27

    I wanted to remove only one param success. Here's how you can do this:

    let params = new URLSearchParams(location.search)
    params.delete('success')
    history.replaceState(null, '', '?' + params + location.hash)
    

    This also retains #hash.


    URLSearchParams won't work on IE, but being worked on for Edge. You can use a polyfill or a could use a naïve helper function for IE-support:

    function take_param(key) {
        var params = new Map(location.search.slice(1).split('&')
            .map(function(p) { return p.split(/=(.*)/) }))   
        var value = params.get(key)
        params.delete(key)
        var search = Array.from(params.entries()).map(
            function(v){ return v[0]+'='+v[1] }).join('&')
        return {search: search ? '?' + search : '', value: value}
    }
    

    This can be used like:

    history.replaceState(
        null, '', take_param('success').search + location.hash)
    

提交回复
热议问题