Reputation: 5037
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]);
});
Upvotes: 284
Views: 453031
Reputation: 6490
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");
To replace current URL without adding it to history entries, use replaceState
:
window.history.replaceState({}, document.title, "/" + "my-new-url.html");
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
We can use:
The pushState()
method if you want to add a new modified URL to history entries.
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.
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 );
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
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;
}
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.
Upvotes: 410
Reputation: 636
I see many here who suggest just doing something like this:
window.history.replaceState(null, '', window.location.pathname);
The problem with this answer is that the parameters are only getting deleted from your search bar while they still exist in url.searchParams
.
For Example:
You're in https://someweb.site/?foo=bar
and window.history.replaceState(null, '', window.location.pathname)
is executed.
You will definitely see https://someweb.site/
now on your search bar. But when you see closely:
for(var [key, value] of url.searchParams.entries()) {
console.log(key+ ' => '+ value);
}
foo => bar
they still exist in url.searchParams
and it can causes you trouble later when you want to add another parameter:
For example, if you want to add name=john
, you'll have suddenly ?foo=bar&name=john
in your browser.
I suggest removing all entries in url.searchParams
first would be a better way:
function deleteAllParams() {
for(var [key, value] of url.searchParams.entries()) {
url.searchParams.delete(key);
}
window.history.replaceState(null, null, url);
}
Upvotes: 0
Reputation: 3790
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, '', window.location.pathname);
Upvotes: 338
Reputation: 211
Here is how can specific query param be removed (even if repeated), without removing other query params:
const newUrl = new URL(location.href);
newUrl.searchParams.delete('deal');
window.history.replaceState({}, document.title, newUrl.href);
Upvotes: 4
Reputation: 81
In Javascript:
window.location.href = window.location.href.split("?")[0]
Upvotes: -3
Reputation: 51
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.
Upvotes: 5
Reputation: 5138
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);
Upvotes: 0
Reputation: 1790
a single line solution :
history.replaceState && history.replaceState(
null, '', location.pathname + location.search.replace(/[\?&]my_parameter=[^&]+/, '').replace(/^&/, '?')
);
credits : https://gist.github.com/simonw/9445b8c24ddfcbb856ec
Upvotes: 1
Reputation: 691
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);
}
}
Upvotes: 30
Reputation: 5211
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'])
Upvotes: 9
Reputation: 458
I belive the best and simplest method for this is:
var newURL = location.href.split("?")[0];
window.history.pushState('object', document.title, newURL);
Upvotes: 36
Reputation: 365
//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;
}
Upvotes: 2
Reputation: 21524
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)
Upvotes: 30
Reputation: 3767
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)
Upvotes: 0
Reputation: 3369
Better solution :
window.history.pushState(null, null, window.location.pathname);
Upvotes: 18
Reputation: 4546
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
Upvotes: 12
Reputation: 3442
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.
Upvotes: 1