Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 521
Aessandro Avatar asked Oct 10 '12 11:10

Aessandro


1 Answers

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

like image 130
Christofer Eliasson Avatar answered Oct 04 '22 17:10

Christofer Eliasson