Javascript根据结果匹配url、if语句的一部分

Javascript根据结果匹配url、if语句的一部分,javascript,Javascript,下面是我试图匹配的url的一个示例: 我试图匹配的是http://store.mywebsite.com/folder-1,除了“folder-1”总是一个不同的值。我不知道如何为此编写if语句: 示例(伪代码) etc我将输入字符串并检查url的单个组件: var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx" // split the string into an array of parts va

下面是我试图匹配的url的一个示例:

我试图匹配的是http://store.mywebsite.com/folder-1,除了“folder-1”总是一个不同的值。我不知道如何为此编写if语句:

示例(伪代码)

etc

我将输入字符串并检查url的单个组件:

var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"

// split the string into an array of parts
var spl = str.split("/");

// spl is now [ http:,,store.mywebsite.com,folder-1,folder-2,item3423434.aspx ]
if (spl[4] == "folder-1") {
    // do something
} else if (spl[4] == "folder-2") {
    // do something else
}
使用此方法也可以轻松地检查URL的其他部分,而不必使用带有子表达式捕获的正则表达式。e、 g.如果spl[5]==“folder-x”,则匹配路径中的第二个目录将是

当然,您也可以使用
indexOf()
,它将返回子字符串匹配在字符串中的位置,但这种方法不是很动态,而且如果存在大量
其他
条件,它也不是很有效/容易读取:

var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
if (str.indexOf("http://store.mywebsite.com/folder-1") === 0) {
    // do something
} else if (str.indexOf("http://store.mywebsite.com/folder-2") === 0) {
    // do something
}

假设基本URL是固定的,并且文件夹编号可能非常大,则此代码应该可以工作:

var url = 'http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx'
  , regex = /^http:..store.mywebsite.com.(folder-\d+)/
  , match = url.match(regex);
if (match) {
  if (match[1] == 'folder-1') {
    // Do this
  } else if (match[1] == 'folder-2') {
    // Do something else
  }
}

只需使用,然后您就可以将URL与简单的字符串条件或正则表达式进行匹配

,从而使事情变得非常简单

if(location.pathname.indexOf("folder-1") != -1)
{
    //do things for "folder-1"
}

如果值“folder-1”可能出现在字符串的其他部分,则可能会出现误报。如果您已经确定情况并非如此,那么提供的示例就足够了。

此解决方案不正确,它会产生错误,location.pathname.indexof不是函数…谢谢!!!你的解决方案是最好的。我刚刚使用了:(window.location.pathname.indexOf($(this.attr(“href”))!=-1),它在Chrome和Firefox上运行良好。谢谢你,这个索引方法的文档太差劲了。
if(location.pathname.indexOf("folder-1") != -1)
{
    //do things for "folder-1"
}