听起来您只需要一些基本的字符串操作。你的意思是这样的?
var url = window.location.pathname.toLowerCase(),
i = -1, // var for indexOf
lookFor = ['/account/logon', '/account/summary'], // what to look for
j = lookFor.length; // var for loop
// remove query
i = url.indexOf('?');
if (i !== -1) { // has query
url = url.slice(0, i); // trim
i = -1; // reset i for later
}
// remove trailing /
while (url.slice(-1) === '/') { // has trailing /
url = url.slice(0, -1); // trim it
}
// trim url in special cases
while (i === -1 && j) { // find a match
i = url.indexOf(lookFor[--j]); // remember to decrease loop counter
}
if (i !== -1) {
i = i + lookFor[j].length; // position of end of match
url = url.slice(0, i); // trim after it
}
url; // resulting url
// Alternately,
// remove query
url = url.split('?', 1)[0]; // get the segment before the first ? (all if no ?)
// remove trailing /
url = url.match(/^([\s\S]*?)\/*$/)[1]; // capture group excludes trailing "/"s
// etc
例子:
http://example.com/some/random///?thing=in_my_url
http://example.com/some/random
http://hilario.us/page/account/summary/place?stuff
http://hilario.us/page/account/summary