[英]How to check if URL has a specific string at the end
我需要根據URL末尾的內容向下滑動疊加層。
如果(URL末尾有'faq'){overlay down down}
你怎么能在jQuery / JavaScript中做到這一點?
如果您的網址類似於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)
一個新方法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:
var currentUrl = window.location.href;
然后你可以使用indexOf來檢查你的令牌是否在字符串的末尾(這里是faq)
if (currentUrl.indexOf('faq') == currentUrl.length - 3)
{
// Do something here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.