如何检查URL末尾是否有特定的字符串

Ale*_*dro 6 javascript url jquery

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

如果(URL末尾有'faq'){overlay down down}

你怎么能在jQuery/JavaScript中做到这一点?

Chr*_*son 11

如果您的网址看起来像这样http://yourdomain.com/faq,您可以这样做:

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

if (lastPart === "faq") {
   // Show your overlay
}
Run Code Online (Sandbox Code Playgroud)

这样就可以检查其他结局并对其采取行动.

更新:

为了使它工作,即使URL有一个尾部斜杠,你可以创建一个这样的函数:

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

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

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

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


com*_*857 9

您应该能够使用带有正则表达式的window.location对象,如下所示:

/faq$/.test(window.location)
Run Code Online (Sandbox Code Playgroud)


Abd*_*auf 6

endsWith()ES6 规范中添加了一种新方法。对于以前的版本,我们可以使用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;
  };
Run Code Online (Sandbox Code Playgroud)

现在你可以轻松地写

If (window.location.href.endsWith("faq")) { 
   // Show your overlay
}
Run Code Online (Sandbox Code Playgroud)

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