我试图删除文档准备浏览器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]);
});

当前回答

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

window.history.replaceState(null, null, window.location.pathname);

其他回答

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

下面是如何删除特定的查询参数(即使是重复的),而不删除其他查询参数:

const newUrl =新的URL(location.href); newUrl.searchParams.delete(“交易”); window.history。replaceState({},文档。标题、newUrl.href);

单行解决方案:

history.replaceState && history.replaceState(
  null, '', location.pathname + location.search.replace(/[\?&]my_parameter=[^&]+/, '').replace(/^&/, '?')
);

致谢:https://gist.github.com/simonw/9445b8c24ddfcbb856ec

我只想删除一个参数成功。你可以这样做:

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

这也保留了#hash。


URLSearchParams不会在IE上工作,但正在为Edge工作。你可以使用polyfill或者可以使用naïve helper函数来支持ie:

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}
}

可以这样使用:

history.replaceState(
    null, '', take_param('success').search + location.hash)
        var currURL = window.location.href;
        var url = (currURL.split(window.location.host)[1]).split("?")[0];
        window.history.pushState({}, document.title, url);

这将是一种只清除查询字符串的更干净的方式。