In my website blog pages added query string in that page URL. I wanted to remove the query string from the URL. So i used to go with jquery and i wrote and added into my scripts. It removes the query string but keep on refreshing the page upto nth time. I used to "one" jquery method. That also doesn't work.
Can you help me
My Script is
jQuery(document).one('ready',function(){
window.location.href = window.location.href.split('?')[0];
});
4 Answers 4
var uri = window.location.href.toString();
if (uri.indexOf("?") > 0) {
var clean_uri = uri.substring(0, uri.indexOf("?"));
window.history.replaceState({}, document.title, clean_uri);
}
2 Comments
setting a value to window.location.href will reload the page. Try this:
var url = window.location.href;
var a = url.indexOf("?");
var b = url.substring(a);
var c = url.replace(b,"");
url = c;
1 Comment
keep on refreshing the page upto nth time.
This is because you are not checking whether the URL has a query string or not. So it is an infinite refresh.
You can try this:
$(document).ready(function(){
if (window.location.href.indexOf('?') > -1) {
window.location.href = window.location.pathname;
}
});
Edit 1: Is it possible to remove query string without page refresh?
You can try this:
$(document).ready(function(){
if (window.location.href.indexOf('?') > -1) {
history.pushState('', document.title, window.location.pathname);
}
});
3 Comments
So if the href is different to the hostname + pathname it has an query. So remove it and refresh the page once:
jQuery(document).one('ready',function(){
if(window.location.href != window.location.hostname + window.location.pathname) {
window.location.href = window.location.pathname;
}
});
window.location.hrefhas?first..indexOf()to check.window.location.hrefhas a?is that the result of split is an array of at least one string. Try for yourself:"https://example.com".split('?')[0]results inhttps://example.com, thus causing a redirect loop when you keep updating window.location.href to itself.