我需要根据URL末尾有一个覆盖图向下滑动。如何检查URL是否在末尾有一个特定的字符串
如果(URL有 '常见问题解答' 末) { 覆盖归结 }
你怎么能做到这一点jQuery的/ JavaScript的?
我需要根据URL末尾有一个覆盖图向下滑动。如何检查URL是否在末尾有一个特定的字符串
如果(URL有 '常见问题解答' 末) { 覆盖归结 }
你怎么能做到这一点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
}
这样可以检查其他结局并对它们采取行动。
更新:
得到它的工作,即使网址有一个尾随斜线,您可以创建这样一个功能:
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/
免责声明:如果您的网址结尾,或查询字符串使用散列,你就必须首先从网址中去除,此脚本才能正常工作
您应该能够使用window.location的对象这一个正则表达式,像这样:
/faq$/.test(window.location)
忽略参数:/path\/to$/.test(window.location.pathname) –
可以使用得到当前的URL:
var currentUrl = window.location.href;
然后你可以使用的indexOf检查,如果您的令牌是字符串(这里FAQ)
012结束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
是您的URL字符串或你的意思是当前网页的网址? –
抱歉,我的错误URL是实际的网页网址... – Alex
您的网址看起来像什么?为了更容易地找出正确的方法 – Salketer