'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?



Solution 1:[1]

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

/faq$/.test(window.location)

If you want to match just the path regardless of query string or hash:

/faq$/.test(window.location.pathname)

Solution 2:[2]

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

Solution 3:[3]

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
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Pierre