Javascript 基于URL位置的Jquery重定向

Javascript 基于URL位置的Jquery重定向,javascript,regex,redirect,Javascript,Regex,Redirect,这就是我试图解决的问题 仅当URL在mydomain.com上显式包含/foldername/index.htm&&/foldername/时,才重定向到 URL是否应该包含任何URL参数/foldername/index.htm?例如,它应该不重定向 所有其他URL不应重定向 这是我的javascript,它是不完整的,但最终是我试图解决的 var locaz=""+window.location; if (locaz.indexOf("mydomain.com") >= 0) {

这就是我试图解决的问题

  • 仅当URL在mydomain.com上显式包含/foldername/index.htm&&/foldername/时,才重定向到
  • URL是否应该包含任何URL参数/foldername/index.htm?例如,它应该不重定向
  • 所有其他URL不应重定向
  • 这是我的javascript,它是不完整的,但最终是我试图解决的

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

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

    该页面是否始终位于同一个域上,如果url包含
    /foldername/pagename.htm
    ,它是否也会包含
    /foldername
    ?因此,
    &&
    检查会有冗余

    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"; 
    }
    
    请尝试下面的代码

    var path = window.location.pathname;
    
    if  ( (path === '/foldername' || path === '/foldername/index.html') && !window.location.search ) {
        alert('should redirect');
    } else {
        alert('should not redirect');
    }
    
    熟悉物体。它提供了
    路径名
    搜索
    主机名
    作为属性,为您省去了RegExp的麻烦(无论如何,您都会喜欢)。您正在寻找以下内容:

    // 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');
    }
    

    我更新描述的目的是为了解决参数和域的问题,但不是当URL显式为“/foldername/pagename.htm”或“/foldername/”时,jack,是的,它将位于同一个域上。此外,我还将页面名称的描述更新为“index.htm”由于/foldername/是文件夹名,没有index.htm,因此如果有人只访问文件夹名或index.htm,他们将被重定向。因此,基本上,您可以访问index.html,或者访问
    /foldername
    /foldername/index.html
    ?是的,这是正确的。显然,我们有一些链接可以将用户直接发送到/foldername/,这与点击/foldername/index.htm相同,但是foldername之后总是有一个/a,这很好
    位置。路径名
    不会包含
    -这在
    位置中可用。搜索
    @rodneyrehm谢谢,当我更新我的答案时忽略了这一点。