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

当前回答

这些解决方案都不适合我,这里有一个兼容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'])

其他回答

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

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

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

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

更好的解决方案:

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

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

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