I saw a bunch of URL splitting techniques on this site but could find one for what i need.
I need the last parameter chopped off.
ie. .aspx?k=website&cs=This%20Site&u=http%3A%2F%2Fwww.website%2FOur-Commitment
to
.aspx?k=website&cs=This%20Site
The URL will not always be the same and so the solution must somehow search for the last "&" and strip it off.
I managed to do this but i was hoping for less lines:
rewriteURL();
function rewriteURL() {
var url = window.location;
var urlparts = url.split(/[\s&]+/);
var newURL = urlparts[0] + '&' + urlparts[1];
window.location.href = newURL;
}
I saw a bunch of URL splitting techniques on this site but could find one for what i need.
I need the last parameter chopped off.
ie. http://www.website./Pages/SearchResultsPage.aspx?k=website&cs=This%20Site&u=http%3A%2F%2Fwww.website.%2FOur-Commitment
to
http://www.website./Pages/SearchResultsPage.aspx?k=website&cs=This%20Site
The URL will not always be the same and so the solution must somehow search for the last "&" and strip it off.
I managed to do this but i was hoping for less lines:
rewriteURL();
function rewriteURL() {
var url = window.location;
var urlparts = url.split(/[\s&]+/);
var newURL = urlparts[0] + '&' + urlparts[1];
window.location.href = newURL;
}
Share
Improve this question
asked Oct 31, 2011 at 19:59
reub77reub77
1,2892 gold badges10 silver badges12 bronze badges
1
- 1 Wouldn't it be better to not rely on order of the parameters and actually remove a specific named parameter? – jfriend00 Commented Oct 31, 2011 at 20:04
4 Answers
Reset to default 4function rewriteURL() {
window.location.href = window.location.href.substring(0, window.location.href.lastIndexOf('&'));
}
var loc = window.location + '';
var url = loc.substring(0, loc.lastIndexOf('&'));
window.location
is not a string.
The answer by @thejh is better, but for a fun one-liner:
var newLoc = location.href.split('&').slice(0,-1).join('&');
// "http://www.website./Pages/SearchResultsPage.aspx?k=website&cs=This%20Site"
function rewriteURL() {
var urlparts = window.location.href.split(/[\s&]+/);
window.location.href = urlparts[0] + '&' + urlparts[1];
}
(Point is, does it matter that much?)
My bigger concern would be that I'd be afraid the parameter order might change, or there'd be additional parameters, etc. Better to do it right and be certain.