【问题标题】:How to check if URL has a specific string at the end如何检查 URL 末尾是否有特定字符串
【发布时间】:2012-09-30 20:51:54
【问题描述】:

我需要根据 URL 末尾的内容来让叠加层向下滑动。

如果(URL 末尾有 'faq') { 覆盖下降 }

你如何在 jQuery/JavaScript 中做到这一点?

【问题讨论】:

标签: javascript jquery url


【解决方案1】:

如果您的 URL 类似于 http://yourdomain.com/faq,您可以执行以下操作:

var url = window.location.href;
var lastPart = url.substr(url.lastIndexOf('/') + 1);

if (lastPart === "faq") {
   // Show your overlay
}

这将使检查其他结局并对其采取行动成为可能。

更新:

要使其正常工作,即使 URL 有斜杠,您也可以创建如下函数:

function getLastPart(url) {
    var parts = url.split("/");
    return (url.lastIndexOf('/') !== url.length - 1 
       ? parts[parts.length - 1]
       : parts[parts.length - 2]);
}

然后您可以调用getLastPart(window.location.href) 之类的函数来获取当前页面 URL 的最后一部分。

这也是一个工作示例:http://jsfiddle.net/WuXHG/

免责声明:如果您的 URL 在末尾使用哈希或查询字符串,您必须先从 URL 中删除 ,以便此脚本正常工作

【讨论】:

  • @Alex 正确,在这种情况下它不起作用。你的地址总是有尾随 /,还是只有一些路径有它?
【解决方案2】:

您应该可以通过正则表达式使用 window.location 对象,如下所示:

/faq$/.test(window.location)

【讨论】:

  • 忽略参数:/path\/to$/.test(window.location.pathname)
【解决方案3】:

在 ES6 规范中添加了一个新方法 endsWith()。对于以前的版本,我们可以使用 polyfill

if (!String.prototype.endsWith)
  String.prototype.endsWith = function(searchStr, Position) {
      // This works much better than >= because
      // it compensates for NaN:
      if (!(Position < this.length))
        Position = this.length;
      else
        Position |= 0; // round position
      return this.substr(Position - searchStr.length,
                         searchStr.length) === searchStr;
  };

现在你可以轻松写了

If (window.location.href.endsWith("faq")) { 
   // Show your overlay
}

参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

【讨论】:

    【解决方案4】:

    您可以使用以下方法获取当前 URL:

     var currentUrl = window.location.href;
    

    然后你可以使用 indexOf 来检查你的令牌是否在字符串的末尾(这里是 faq)

     if (currentUrl.indexOf('faq') == currentUrl.length - 3)
     {
      // Do something here
     }
    

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多