【问题标题】:Javascript URL redirect if URL starts with a string如果 URL 以字符串开头,则 Javascript URL 重定向
【发布时间】:2018-07-13 22:47:11
【问题描述】:

如果有人使用以字符串开头的 URL 登陆页面,我想将他们重定向到另一个页面。

例如,访问者登陆website.com/all-books/bookTitle 我想将它们重定向到website.com/bookTitle

但我也有website.com/all-books/,我不希望访问者在登陆时被重定向。

我试过了,但没用:

var fromUrl = '/all-books/';
var toUrl = '/';

var fromRegex = "^\\" + fromUrl + "\\/?$";
var match = location.pathname.match(new RegExp(fromRegex, 'i'));
if (match && !window.frameElement) {
  window.location.replace(toUrl);
}

感觉应该是直截了当的,但我无法将各个部分组合在一起。我会很感激任何帮助。提前致谢!

【问题讨论】:

  • 请分享您的代码。
  • @JorgeMejia 是的,刚刚添加。
  • 我不确定你的正则表达式是否正确

标签: javascript url redirect


【解决方案1】:

如果您可以粘贴到目前为止的相关代码,将会有所帮助。 这样的事情可能会有所帮助:

var url = window.location.href;
var n = url.lastIndexOf('/');
var uniquekey = url.substring(n + 1);
window.location.replace("website.com/"+uniquekey);

【讨论】:

    【解决方案2】:

    我认为您没有正确处理正则表达式。

    您必须正确过滤 url,如果匹配,则通过删除要禁用的目录来替换它。

    试试这个:

    const openedUrl = window.location.href;
    let regexPattern = "http.+\/all-books\/.*";
    const regexObj = new RegExp(regexPattern);
    
    if(openedUrl.match(regexObj)){
        dirToRemove = "all-books/";
        indexOf = openedUrl.indexOf(dirToRemove);
        const newUrl = openedUrl.slice(0, indexOf) + openedUrl.slice(indexOf+dirToRemove.length);
    window.location.replace(newUrl);
    
    };
    

    我仍然认为最好使用 httpaccess 文件来确保发生干净的重定向。此外,如果您使用 node.js 或 python 等来呈现网站并在此地址上返回 302 重定向,则可以使用服务器脚本。

    上面的脚本也应该可以工作,只要客户端当然允许编写脚本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-11
      相关资源
      最近更新 更多