Scott Scott - 3 years ago 138
Javascript Question

Wildcard for domain URL in if statement (JavaScript)

I'm trying to hide a particular div (id=contactinfo) on the page when the current URL ends in /folder1/. For example:


Here's what I have, which doesn't hide the div:

<script type="text/javascript">
if (window.location.href.toLowerCase() == "[^ ]*/folder1/".toLowerCase()) {
else {

I'm new to JavaScript and suspect there might be a problem with using regex in a literal comparison. Any suggestions would be greatly appreciated.

Answer Source

Why regex ...?

You want to know if the current path ends in /folder1‌​/, regardless of case - so let's do just that, get the last 9 characters of the lower-cased path, and do a simple string comparison:

window.location.pathname.toLowerCase().substr(-9) == '/folder1‌​/'

The "condensed" version, this is all you need if you want to keep it short:

document.getElementById('contactinfo').style.display = 
  (window.location.pathname.toLowerCase().substr(-9) == '/folder1‌​/' ? 'none' : 'block');

(() optional, but they add a bit of readability.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download