JavaScript current URL check

I am wondering how I would get JavaScript to check if a user is on a certain URL so i can build an if statement from the result.

My reasoning is that if a user clicks on a link in the menu and they are currently on trucks.php the javascript will redirect them to a certain page. If they are not on trucks.php they will be directed to a different page.

Cheers guys.

Answers


The current location is in location.href.

The location object also contains some other useful fields:

  • location.hash: The part after the # in the URL
  • location.host: Hostname including port (if specified)
  • location.hostname: Just the hostname
  • location.pathname: The requested URI without protocol/host/port; starting with a /
  • location.port: The port - only if one is specified in the URL
  • location.protocol: Usually 'http:' or 'https:' - mind the colon at the end

In your case the most fail-safe way to check if the filename is trucks.php is this:

var parts = location.pathname.split('/');
if(parts[parts.length - 1] == 'trucks.php') {
    location.href = 'some-other-page';
}

If you want to redirect without keeping the current page in history, use the following code instead of the location.href assignment:

location.replace('some-other-page');

Need Your Help

DataGrid in WPF

wpf .net-3.5

Datagrid control is missing in Toolbox. I tried to add it from WPF components, but it is not listing there also. And iam using 3.5 framework

Web scraping with Python

python screen-scraping

I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.