Jquery重定向基于URL位置

时间:2013-03-28 13:37:10

标签: javascript regex redirect

这就是我想要解决的......

  1. 仅当网址明确包含/foldername/index.htm&& / foldername / on mydomain.com然后重定向到http://www.example.com
  2. 如果网址包含任何网址参数/foldername/index.htm?example,则不会重定向
  3. 所有其他网址不应重定向
  4. 这是我的javascript不完整,但最终我正在努力解决...

    var locaz=""+window.location;
    if (locaz.indexOf("mydomain.com") >= 0) {
        var relLoc = [
            ["/foldername/index.htm"],
            ["/foldername/"]
        ];
        window.location = "http://www.example.com"; 
    }
    

    这是为了管理某些用户根据书签等特定方式点击的URL。在不删除页面的情况下,我们希望在采取进一步行动之前监控有多少人访问该页面。

3 个答案:

答案 0 :(得分:1)

页面是否始终位于同一个域中,如果网址包含/foldername/pagename.htm,它是否也会包含/foldername?因此&&检查会有多余的。

请尝试以下代码。

var path = window.location.pathname;

if  ( (path === '/foldername' || path === '/foldername/index.html') && !window.location.search ) {
    alert('should redirect');
} else {
    alert('should not redirect');
}

答案 1 :(得分:0)

var url = window.location;
var regexDomain = /mydomain\.com\/[a-zA-Z0-9_\-]*\/[a-zA-Z0-9_\-]*[\/\.a-z]*$/    
if(regexDomain.test(url)) { 
  window.location = "http://www.example.com"; 
}

答案 2 :(得分:0)

熟悉location对象。它提供了pathnamesearchhostname作为属性,让您免于RegExp麻烦(无论如何,您最喜欢get wrong)。您正在寻找以下内容:

// no redirect if there is a query string
var redirect = !window.location.search 
  // only redirect if this is run on mydomain.com or on of its sub-domains
  && window.location.hostname.match(/(?:^|\.)mydomain\.com$/)
  // only redirect if path is /foldername/ or /foldername/index.html
  && (window.location.pathname === '/foldername/' || window.location.pathname === '/foldername/index.html');

if (redirect) {
  alert('boom');
}
相关问题