我试图删除文档准备浏览器url中的“?”后的所有内容。

以下是我正在尝试的:

jQuery(document).ready(function($) {

var url = window.location.href;
    url = url.split('?')[0];
});

我可以这样做,并看到下面的工作:

jQuery(document).ready(function($) {

var url = window.location.href;
    alert(url.split('?')[0]);
});

当前回答

运行这个js为我清除了当前url上的任何参数,而不刷新页面。

window.history.replaceState({}, document.title, location.protocol + '//' + location.host + location.pathname);

其他回答

如果我在URL的末尾有一个特殊的标签,比如:http://domain.com/?tag=12345 下面是删除标签的代码,只要它出现在URL中:

<script>
// Remove URL Tag Parameter from Address Bar
if (window.parent.location.href.match(/tag=/)){
    if (typeof (history.pushState) != "undefined") {
        var obj = { Title: document.title, Url: window.parent.location.pathname };
        history.pushState(obj, obj.Title, obj.Url);
    } else {
        window.parent.location = window.parent.location.pathname;
    }
}
</script>

这就给出了从URL中删除一个或多个(或全部)参数的想法

window。location。pathname基本上得到'之前的所有内容?在url中。

Var pathname = window.location.pathname;//只返回路径 Var url = window.location.href;//返回完整URL

一个简单的方法做到这一点,工作在任何页面,需要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);
   }
}

这些都是误导,你永远不想添加到浏览器历史记录,除非你想在单页应用程序中进入不同的页面。如果你想在不改变页面的情况下删除参数,你必须使用:

window.history.replaceState(null, null, window.location.pathname);
//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;     
}

这些解决方案都不适合我,这里有一个兼容ie11的功能,也可以删除多个参数:

/**
* 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'])