从值数组中查找URL字符串?

时间:2011-09-20 16:48:05

标签: javascript jquery

我想在URL字符串中查找数组值?检查条件如果请求的URL包含数组值,则传递条件,否则重定向到google.com

例如

     $(document).ready(function () {
        var urls = ["/dept/ce/",
                      "/dept/cs",
                      "/dept/career",
                      "/dept/it",
                      "/dept/mkt/",
                      "/dept/Membership/"
                      , "/dept/pr"
                      , "/dept/PS"
                      , "/dept/ta"
                      , "/dept/wc"
                      , "/dept/PubsProducts"
                      , "_layouts/settings.aspx"
                      ,"/_catalogs/masterpage/"];

       //If document.location.href = "http://localhost/dept/ce/default.aspx" 
       //And Array has "/dept/ce" values
       //Now check document.location.href against array values, if    
      //document.location.href contains array values then pass condition otherwise 
      //else condition 
    });

怎么做?

1 个答案:

答案 0 :(得分:3)

如果当前位置网址包含数组中的任何字符串,我相信你想要做某事。既然你已经使用了jQuery,我推荐使用jQuery.grep。

示例:

if ($.grep(urls, function(str) { return location.href.indexOf(str) > -1; }).length > 0) {
  // do one thing
} else {
  // do another thing
}

链接:http://api.jquery.com/jQuery.grep/