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

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


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

/faq$/.test(window.location)

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