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

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

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

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

如果您的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中删除,以使此脚本正常工作

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

 /faq$/.test(window.location) 

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

  var currentUrl = window.location.href; 

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

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

一个新方法endsWith()已添加到ES6规范中。 对于以前的版本,可以使用添加

 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