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:

http://example.com/folder1/

https://example1.net/FOLDER1/

example2.org/Folder1/

example3.com/folder1/

subdomain.example.com/folder1/

intranet/folder1/

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

<script type="text/javascript">
if (window.location.href.toLowerCase() == "[^ ]*/folder1/".toLowerCase()) {
document.getElementById("contactinfo").style.display="none";
}
else {
document.getElementById("contactinfo").style.display="block";
}
</script>


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