我会split()
字符串和检查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
}
使用这种方法可以很容易地查询的网址过多的其他部分,而不必使用与子表达式捕获正则表达式。例如匹配路径中的第二个目录将是if spl[5] == "folder-x"
。
当然,你也可以使用indexOf()
,它会返回一个字符串中子字符串匹配的位置,但是这个方法并不像动态一样,并且它不是非常有效/易于阅读,如果将要有一个很多else
条件:
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
}
这种解决方案是不正确的,它产生的错误,location.pathname.indexof不是一个功能... – chhameed 2012-04-04 16:12:09
谢谢!您的解决方案是最好的。我刚刚使用: (window.location.pathname.indexOf($(this).attr(“href”))!= - 1),它在Chrome和Firefox上运行良好。谢谢你,这个文档对于这个indexof方法来说太蹩脚了。 – Polopollo 2013-02-06 11:37:41