Javascript 从url中查找和删除未知值

Javascript 从url中查找和删除未知值,javascript,url,Javascript,Url,我正在写一点js,这会对路径名进行一些清理。到目前为止,我有以下几点: var corePageUrl = window.location.pathname.toLowerCase(); if (corePageUrl.indexOf("/account/logon")>=0||corePageUrl.indexOf("/account/summary")>=0)) { // do function here } 基本上,该函数需要执行以下操作:获取路径名,从中除去尾随

我正在写一点js,这会对路径名进行一些清理。到目前为止,我有以下几点:

var corePageUrl = window.location.pathname.toLowerCase();
if (corePageUrl.indexOf("/account/logon")>=0||corePageUrl.indexOf("/account/summary")>=0)) {
  // do function here    
}
基本上,该函数需要执行以下操作:获取路径名,从中除去尾随/如果除了这两个限定if语句的
.indexOf
语句之外还有其他语句,则将其除去。无数的谷歌搜索让我一事无成,当我开始处理更复杂的javascript问题时,这让我不知所措


我并不是要求任何人为我编写代码,更重要的是,请帮助我了解将导致我获得所需结果的逻辑。

听起来你只需要一些基本的字符串操作。你是说像这样的

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


示例:

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

如果我理解正确,您希望函数执行以下操作:

输入
http://www.example.com/account/logon/foo?bar=baz

输出
http://www.example.com/account/logon

您可以使用正则表达式轻松地实现这一点,并捕获要匹配的URL部分

var url = window.location.pathname.toLowerCase(),
    match;

if (match = url.match(/.*\/account\/(?:logon|summary)/)) {
    // do function here    
}

其中
match
将包含URL,其中包括
/account/logon
/account/summary

之前的所有内容。这是否也可以用于切分查询字符串参数?如果在
查找
中存在与项目匹配的内容,则为“是”。如果你想在任何情况下删除
,那么在删除尾部的
/
s之前先删除。我并不是说这些代码都经过了优化(例如,修剪可以更改为使用
slice
最少次数),但我刚刚意识到删除查询可以非常快速地完成
url=url.split(“?”,1)[0]; // 在第一节之前获取片段?(如果没有,全部?
。如果您对RegExp感到满意,那么您可以通过
url=url.match(/^([\s\s]*?)\/*$/)[1]进行修剪。为什么我在睡觉前会想这些事情?
var url = window.location.pathname.toLowerCase(),
    match;

if (match = url.match(/.*\/account\/(?:logon|summary)/)) {
    // do function here    
}