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

博士TL;

1-修改当前URL并添加/注入它(新的修改URL)作为一个新的URL条目到历史列表,使用pushState:

window.history.pushState({}, document.title, "/" + "my-new-url.html");

2-替换当前URL而不添加到历史条目,使用replaceState:

window.history.replaceState({}, document.title, "/" + "my-new-url.html");

3-根据您的业务逻辑,pushState将在以下情况下有用:

您希望支持浏览器的后退按钮 你想要创建一个新的URL,添加/插入/推送新的URL到历史条目,并使其成为当前URL 允许用户使用相同的参数收藏页面(以显示相同的内容) 通过statobj以编程方式访问数据,然后从锚解析


正如我从你的评论中理解的那样,你想要在不重定向的情况下清理你的URL。

注意,您不能更改整个URL。您可以更改域名后面的内容。这意味着您不能更改www.example.com/,但可以更改。com/之后的内容

www.example.com/old-page-name => can become =>  www.example.com/myNewPaage20180322.php

背景

我们可以用:

1-如果你想添加一个新的修改URL到历史条目,使用pushState()方法。

2-如果你想更新/替换当前历史条目,使用replaceState()方法。

. replacestate()的操作与. pushstate()完全相同,除了. replacestate()修改当前历史条目,而不是创建一个新条目。注意,这并不会阻止在全局浏览器历史记录中创建新条目。


.replaceState()在需要更新 状态对象或当前历史记录项的URL,以响应某些 用户操作。


Code

To do that I will use The pushState() method for this example which works similarly to the following format:

var myNewURL = "my-new-URL.php";//the new URL
window.history.pushState("object or string", "Title", "/" + myNewURL );

Feel free to replace pushState with replaceState based on your requirements.

You can substitute the paramter "object or string" with {} and "Title" with document.title so the final statment will become:

window.history.pushState({}, document.title, "/" + myNewURL );

Results

The previous two lines of code will make a URL such as:

https://domain.tld/some/randome/url/which/will/be/deleted/

To become:

https://domain.tld/my-new-url.php

Action

Now let's try a different approach. Say you need to keep the file's name. The file name comes after the last / and before the query string ?.

http://www.someDomain.com/really/long/address/keepThisLastOne.php?name=john

Will be:

http://www.someDomain.com/keepThisLastOne.php

Something like this will get it working:

 //fetch new URL
 //refineURL() gives you the freedom to alter the URL string based on your needs. 
var myNewURL = refineURL();

//here you pass the new URL extension you want to appear after the domains '/'. Note that the previous identifiers or "query string" will be replaced. 
window.history.pushState("object or string", "Title", "/" + myNewURL );


//Helper function to extract the URL between the last '/' and before '?' 
//If URL is www.example.com/one/two/file.php?user=55 this function will return 'file.php' 
 //pseudo code: edit to match your URL settings  

   function refineURL()
{
    //get full URL
    var currURL= window.location.href; //get current address
    
    //Get the URL between what's after '/' and befor '?' 
    //1- get URL after'/'
    var afterDomain= currURL.substring(currURL.lastIndexOf('/') + 1);
    //2- get the part before '?'
    var beforeQueryString= afterDomain.split("?")[0];  
 
    return beforeQueryString;     
}

UPDATE:

For one liner fans, try this out in your console/firebug and this page URL will change:

    window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);

This page URL will change from:

http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103

To

http://stackoverflow.com/22753103#22753103

Note: as Samuel Liew indicated in the comments below, this feature has been introduced only for HTML5.

An alternative approach would be to actually redirect your page (but you will lose the query string `?', is it still needed or the data has been processed?).

window.location.href =  window.location.href.split("?")[0]; //"http://www.newurl.com";

Note 2:

Firefox seems to ignore window.history.pushState({}, document.title, ''); when the last argument is an empty string. Adding a slash ('/') worked as expected and removed the whole query part of the url string. Chrome seems to be fine with an empty string.


清除所有参数,不做页面刷新,如果你使用HTML5,那么你可以这样做:

历史。pushState({}, ", 'index.html');//将index.html替换为你的页面名称

这将在浏览器历史记录中添加一个条目。如果不想添加新条目而只想替换旧条目,还可以考虑replaceState。


如果我在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.pushState(null, null, window.location.pathname);

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

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

在Javascript中:

window.location.href =  window.location.href.split("?")[0]

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

(l=>{window.history.replaceState({},'',l.pathname+l.hash)})(location)

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

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)

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

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

单行解决方案:

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

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


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

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

        var currURL = window.location.href;
        var url = (currURL.split(window.location.host)[1]).split("?")[0];
        window.history.pushState({}, document.title, url);

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


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

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