Remove URL parameters without refreshing page

前端 未结 13 963
执念已碎
执念已碎 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:13

    Better solution :

    window.history.pushState(null, null, window.location.pathname);
    
    0 讨论(0)
  • 2020-12-07 08:15

    None of these solutions really worked for me, here is a IE11-compatible function that can also remove multiple parameters:

    /**
    * Removes URL parameters
    * @param removeParams - param array
    */
    function removeURLParameters(removeParams) {
      const deleteRegex = new RegExp(removeParams.join('=|') + '=')
    
      const params = location.search.slice(1).split('&')
      let search = []
      for (let i = 0; i < params.length; i++) if (deleteRegex.test(params[i]) === false) search.push(params[i])
    
      window.history.replaceState({}, document.title, location.pathname + (search.length ? '?' + search.join('&') : '') + location.hash)
    }
    
    removeURLParameters(['param1', 'param2'])
    
    0 讨论(0)
  • 2020-12-07 08:15

    In jquery use <

    window.location.href =  window.location.href.split("?")[0]
    
    0 讨论(0)
  • 2020-12-07 08:21

    a simple way to do this, works on any page, requires HTML 5

    // get the string following the ?
    var query = window.location.search.substring(1)
    
    // is there anything there ?
    if(query.length) {
       // are the new history methods available ?
       if(window.history != undefined && window.history.pushState != undefined) {
            // if pushstate exists, add a new state to the history, this changes the url without reloading the page
    
            window.history.pushState({}, document.title, window.location.pathname);
       }
    }
    
    0 讨论(0)
  • 2020-12-07 08:21
    //Joraid code is working but i altered as below. it will work if your URL contain "?" mark or not
    //replace URL in browser
    if(window.location.href.indexOf("?") > -1) {
        var newUrl = refineUrl();
        window.history.pushState("object or string", "Title", "/"+newUrl );
    }
    
    function refineUrl()
    {
        //get full url
        var url = window.location.href;
        //get url after/  
        var value = url = url.slice( 0, url.indexOf('?') );
        //get the part after before ?
        value  = value.replace('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]','');  
        return value;     
    }
    
    0 讨论(0)
  • 2020-12-07 08:23

    I belive the best and simplest method for this is:

    var newURL = location.href.split("?")[0];
    window.history.pushState('object', document.title, newURL);
    
    0 讨论(0)
提交回复
热议问题