How to check if URL has a specific string at the end
I need to get an overlay to slide down based on what the URL has at the end of it.
If (URL has 'faq' at the end) { overlay comes down }
How can you do that in jQuery/JavaScript?
If your URL looks something like this http://yourdomain.com/faq
, you could do something like this:
var url = window.location.href;
var lastPart = url.substr(url.lastIndexOf('/') + 1);
if (lastPart === "faq") {
// Show your overlay
}
This would make it possible to check for other endings and act on them as well.
Update:
To get it working, even if the URL has a trailing slash, you could create a function like this:
function getLastPart(url) {
var parts = url.split("/");
return (url.lastIndexOf('/') !== url.length - 1
? parts[parts.length - 1]
: parts[parts.length - 2]);
}
You could then call the function like getLastPart(window.location.href)
to get the last part of the URL for the current page.
Here is a working example as well: http://jsfiddle.net/WuXHG/
Disclaimer: If your URLs use hashes at the end, or a querystring, you would have to strip the from the URL first, for this script to work properly
您应该可以使用window.location对象来使用正则表达式,如下所示:
/faq$/.test(window.location)
You can get the current URL using :
var currentUrl = window.location.href;
Then you can use indexOf to check if your token is in the end of string (here faq)
if (currentUrl.indexOf('faq') == currentUrl.length - 3)
{
// Do something here
}
链接地址: http://www.djcxy.com/p/83898.html
上一篇: 如何在字符串上实现“EndsWith”?