最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Split URL in javascript at last instance of '&' - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 4
function 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.

发布评论

评论列表(0)

  1. 暂无评论