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

当前回答

如果我在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

其他回答

在Javascript中:

window.location.href =  window.location.href.split("?")[0]
//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;     
}

下面是ES6的一行代码,它保留了位置散列,并且使用replaceState不会污染浏览器历史记录:

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

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

我认为最好和最简单的方法是:

var newURL = location.href.split("?")[0];
window.history.pushState('object', document.title, newURL);