198

I am trying to remove everything after the "?" in the browser url on document ready.

Here is what I am trying:

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

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

I can do this and see it the below works:

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

var url = window.location.href;
    alert(url.split('?')[0]);
});
Samuel Liew
  • 68,352
  • 105
  • 140
  • 225
Derek
  • 3,981
  • 6
  • 34
  • 72
  • Have two forms on one page and when one form is submitted it adds a product to cart and appends a long parameter to the url after the page refreshes. So I want to be able to remove that parameter when the document is ready and it starts with a ? – Derek Mar 31 '14 at 03:16
  • 1
    If you want to refresh the page, why wait for `.ready()`? You don't need to wait in order to redirect to a new URL or just use `.pushState()` as Joraid recommended. – jfriend00 Mar 31 '14 at 03:33
  • `window.history.replaceState({}, document.title, window.location.pathname);` – Ehsan Chavoshi May 12 '21 at 13:28

15 Answers15

295

TL;DR

1- To modify current URL and add / inject it (the new modified URL) as a new URL entry to history list, use pushState:

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

2- To replace current URL without adding it to history entries, use replaceState:

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

3- Depending on your business logic, pushState will be useful in cases such as:

  • you want to support the browser's back button

  • you want to create a new URL, add/insert/push the new URL to history entries, and make it current URL

  • allowing users to bookmark the page with the same parameters (to show the same contents)

  • to programmatically access the data through the stateObj then parse from the anchor


As I understood from your comment, you want to clean your URL without redirecting again.

Note that you cannot change the whole URL. You can just change what comes after the domain's name. This means that you cannot change www.example.com/ but you can change what comes after .com/

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

Background

We can use:

1- The pushState() method if you want to add a new modified URL to history entries.

2- The replaceState() method if you want to update/replace current history entry.

.replaceState() operates exactly like .pushState() except that .replaceState() modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.


.replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.


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.

Mohammed Joraid
  • 4,974
  • 2
  • 20
  • 35
  • 3
    You forgot to mention that this is a HTML5-feature only. https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries – Samuel Liew Mar 31 '14 at 03:21
  • Why are you stripping from the last slash? What does that have to do with the OP's question? They just want to get rid of query string. The first question mark defines the beginning of the query string. – jfriend00 Mar 31 '14 at 03:36
  • 6
    `replaceState` seems like a better fit, but `pushState` will work as well, that is until you start clicking the back and forward buttons in the browser and you realize there's a reason there's entire libraries for working with the History API. – adeneo Mar 31 '14 at 03:39
  • @jfriend00 based on the behaviour of the function, what you add in the third paramter will be placed in the URL after the domain name, meanas after the domain / as in www.example.com/. There is a chance that the OP may have several / between the domain name and ? in case the website is in a sub directory, therefore, it's up to him/her to excersise and do a better url refinement since the question was about how to chagne the url, now how to get it correctly. – Mohammed Joraid Mar 31 '14 at 03:46
  • I'm just saying that you don't need this `url.substring(url.lastIndexOf('/') + 1);` at all. `url.split("?")[0]` will get the part before the first question mark which is all I think the OP asked for. The OP's question asks: "I am trying to remove everything after the "?" in the browser url". – jfriend00 Mar 31 '14 at 03:50
  • @jfriend00 To redirect, you are correct, but to use pushState then the URL will be repeated. E.g www.example.com/file.php?id=25 if you get everything before ? it will be www.example.com/file.php if you add it to pushState then it will be added after/ as in www.example.com/www.example.com/file.php so that's why I get only file.php. But window.location.href to be used, then yes, getting everything before the ? is what we need. – Mohammed Joraid Mar 31 '14 at 03:57
  • 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 the the history, this changes the url without reloading the page window.history.pushState({}, document.title, window.location.pathname); } } – Afsal KK Feb 22 '17 at 09:33
  • in function refineUrl() it should be var value = url.substring(url.indexOf('/') + 1); instead of var value = url.substring(url.lastIndexOf('/') + 1); – code chimp Mar 15 '17 at 07:17
  • @codechimp You had it the other way around. I think what you meant is: ** window.history.pushState("object or string", "Title", "/");** That like only will clear everything after the .com/ including the / However, the code in the answer will keep the page's name. It will only clear any directory, MVC hierarchy visible in the URL. – Mohammed Joraid May 04 '17 at 03:22
  • You put a lot of effort into this answer, which I appreciate, but `pushState` really isn't such a good idea. `replaceState` is just as effective, but without any of the negative side effects that come with `pushState`. Hence, [Evan's answer](https://stackoverflow.com/a/41061471/5872029) is a better solution. – Tijmen Oct 04 '17 at 10:51
  • @Tijmen Indeed. Thank you for your comment. I have updated my answer to incorporate `replaceState`. However, the OP asked about how to remove parameters after `?` from showing in URL. This can be somehow troublesome when a user tries to bookmark the address "including parameters" in order to show the same web page content or support browser back button. – Mohammed Joraid Oct 12 '17 at 17:55
  • If i use pushstate to clear parameters from url will i still be able to use those parameters in my code? – mondi Dec 25 '17 at 09:05
  • 1
    Life Saver!!!!!!!! – Dr. Div Feb 02 '21 at 04:27
202

These are all misleading, you never want to add to the browser history unless you want to go to a different page in a single page app. If you want to remove the parameters without a change in the page, you must use:

window.history.replaceState(null, null, window.location.pathname);
evanjmg
  • 2,391
  • 1
  • 12
  • 11
  • 12
    KISS (Keep is stupid and simple). The OP asked to remove all after the ? and this is the simplest answer you can get for what he asked for! – Warface Aug 28 '19 at 14:08
  • Didn't work on firefox. On refresh, get parameters still appear. Works using both push and replace. window.history.replaceState({page: location.pathname}, document.title, window.location.pathname); window.history.pushState({page: location.pathname}, document.title, window.location.pathname); – Ajay Singh Jan 11 '20 at 08:22
  • 1
    history.replaceState(null, null, location.pathname + location.hash) -- add location.hash if you don't want to remove that part – eselk Feb 13 '20 at 18:02
  • 2021 and it works on firefox aswell – Gabriel G Feb 01 '21 at 15:28
30

a simple way to do this, works on any page, requires 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);
   }
}
pnizzle
  • 5,359
  • 3
  • 38
  • 70
  • This works amazingly well. Unfortunately, I don't have the first clue as to why it work. Grateful all the same. – Matt Cremeens Feb 07 '17 at 16:47
  • 1
    the first two lines check if there is anything after the ? (substring just removes the '?') then i check if the browser supports the new pushstate call, and finally i use pushstate to add a state to the stack of urls (you can push and pop urls on that stack), window.location.pathname is a local url minus the query and minus the domain name and prefix (http://domain.com/THIS?notthis) – Martijn Scheffer Feb 09 '17 at 18:38
  • see https://developer.mozilla.org/en-US/docs/Web/API/History_API#Example_of_pushState()_method – Martijn Scheffer Feb 09 '17 at 18:43
27

I belive the best and simplest method for this is:

var newURL = location.href.split("?")[0];
window.history.pushState('object', document.title, newURL);
ChristianG
  • 368
  • 3
  • 11
12

Better solution :

window.history.pushState(null, null, window.location.pathname);
Matrix
  • 2,783
  • 6
  • 29
  • 59
12

I wanted to remove only one param success. Here's how you can do this:

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

This also retains #hash.


URLSearchParams won't work on IE, but being worked on for Edge. You can use a polyfill or a could use a naïve helper function for IE-support:

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

This can be used like:

history.replaceState(
    null, '', take_param('success').search + location.hash)
odinho - Velmont
  • 18,214
  • 6
  • 38
  • 30
  • Great solution, is there any way to not add the '?' if no params are passed? – ricks Nov 12 '18 at 22:00
  • 2
    @RickS Of course, the `take_param` is already doing that, but you can make the `URLSearchParams` do the same by doing: `history.replaceState(null, '', (params ? '?' + params : '') + location.hash)`. Or however you like. – odinho - Velmont Nov 13 '18 at 17:42
11

if I have a special tag at the end of my URL like: http://domain.com/?tag=12345 Here is the below code to remove that tag whenever it presents in the 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>

This gives the idea to remove one or more (or all) parameters from URL

With window.location.pathname you basically get everything before '?' in the url.

var pathname = window.location.pathname; // Returns path only

var url = window.location.href; // Returns full URL

Community
  • 1
  • 1
Tarik
  • 3,543
  • 31
  • 29
8

None of these solutions really worked for me, here is a IE11-compatible function that can also remove multiple parameters:

/**
* 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'])
Fabian von Ellerts
  • 3,261
  • 28
  • 31
3
        var currURL = window.location.href;
        var url = (currURL.split(window.location.host)[1]).split("?")[0];
        window.history.pushState({}, document.title, url);

This will be a cleaner way to clear only query string.

Jeevath
  • 31
  • 2
2
//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;     
}
chozha rajan
  • 325
  • 3
  • 14
1

To clear out all the parameters, without doing a page refresh, AND if you are using HTML5, then you can do this:

history.pushState({}, '', 'index.html' ); //replace 'index.html' with whatever your page name is

This will add an entry in the browser history. You could also consider replaceState if you don't wan't to add a new entry and just want to replace the old entry.

Josh
  • 3,115
  • 5
  • 22
  • 42
1

a single line solution :

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

credits : https://gist.github.com/simonw/9445b8c24ddfcbb856ec

Mohamed23gharbi
  • 1,406
  • 20
  • 26
0

In jquery use <

window.location.href =  window.location.href.split("?")[0]
Petter Friberg
  • 19,652
  • 9
  • 51
  • 94
Partha
  • 79
  • 7
0

Here is an ES6 one liner which preserves the location hash and does not pollute browser history by using replaceState:

(l=>{window.history.replaceState({},'',l.pathname+l.hash)})(location)
joeyhoer
  • 3,057
  • 1
  • 15
  • 21
  • Could you add some more info about this, it is hard to understand what this is doing. – ricks Nov 12 '18 at 21:46
  • 2
    @RickS It's an IIFE (immediately invoked function expression) that's why it's wrapped in parenthesis ()(location) the first parenthesis makes it able to stay on it's own as anonymous function, the (location) at the end immediately invokes the function passing it the global `location` aka `window.location` object, so the function has access to the globals `location` as `l` the rest is basic replaceState as in all other answers, he's concatenating the pathname and hash (example.com/#hash) as the new url. Hope it's digestible, if not let me know – Can Rau Apr 20 '19 at 16:02
  • @Can why not just use `window.history.replaceState({}, '', location.pathname + location.hash)`? ;) – Fabian von Ellerts Oct 22 '19 at 10:16
  • @FabianvonEllerts Good question actually, not really sure only thing is you don't have to write `location` 2 times yet don't need to assign it to a variable or is there more to it Joey? – Can Rau Oct 23 '19 at 18:37
0

Running this js for me cleared any params on the current url without refreshing the page.

window.history.replaceState({}, document.title, location.protocol + '//' + location.host + location.pathname);
joshmoto
  • 3,083
  • 1
  • 12
  • 28