How to check if URL has a specific string at the e

2019-06-22 07:12发布

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?

4条回答
祖国的老花朵
2楼-- · 2019-06-22 07:25

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

查看更多
爷的心禁止访问
3楼-- · 2019-06-22 07:26

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
 }
查看更多
The star\"
4楼-- · 2019-06-22 07:32

You should be able to use the window.location object for this with a regexp, something like this:

/faq$/.test(window.location)
查看更多
小情绪 Triste *
5楼-- · 2019-06-22 07:33

A new method endsWith() has been added to the ES6 specification. For previous versions we can polyfill it using

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;
  };

Now you can easily write

If (window.location.href.endsWith("faq")) { 
   // Show your overlay
}

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

查看更多
登录 后发表回答