2010-06-07 18 views
1

这里是网址我试图匹配的例子:http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx网址Javascript的比赛的一部分,如果基于结果的语句

什么我尝试匹配是http://store.mywebsite.com/folder -1,但“文件夹-1”将始终是不同的值。我无法弄清楚如何写一个if语句此:

例(伪代码)

if(url contains http://store.mywebsite.com/folder-1) 
do this 

else if (url contains http://store.mywebsite.com/folder-2) 
do something else 

回答

3

我会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 
} 
0

假设基本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 
    } 
} 
4

在让事情很简单的利益......

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

这可能会给你误报,如果值“文件夹1”可能存在于其他地方的字符串。如果您已经确认情况并非如此,则所提供的示例应该足够。

+0

这种解决方案是不正确的,它产生的错误,location.pathname.indexof不是一个功能... – chhameed 2012-04-04 16:12:09

+0

谢谢!您的解决方案是最好的。我刚刚使用: (window.location.pathname.indexOf($(this).attr(“href”))!= - 1),它在Chrome和Firefox上运行良好。谢谢你,这个文档对于这个indexof方法来说太蹩脚了。 – Polopollo 2013-02-06 11:37:41