0

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.

2
  • 2
    "suspect there might be a problem with using regex in a literal comparison" — Well. Yes. How about typing "JavaScript regular expression" into Google and finding out how to use regular expressions properly? Commented Sep 29, 2017 at 19:52
  • You should use the test method of regular expressions : javascriptkit.com/jsref/regexp.shtml Commented Sep 29, 2017 at 19:55

3 Answers 3

1

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.)

Sign up to request clarification or add additional context in comments.

Comments

0

You can use RegExp /folder1/i, note the case insensitive flag, RegExp.prototype.test() which returns a Boolean and .pathname of location

if (/folder1/i.test(location.pathname)) {
  // do stuff
}

Comments

0

Regular expressions in JavaScript aren't just strings, but are encapsulated in / like this:

const regex = /\/folder1\/?$/i

Note the $ in the RegEx. It makes the regex match only if the folder1 is at the end and the ? makes the last slash optional. The i at the end denotes that uppercase or lowercase doesn't matter.

You can compare the current URL against that regex by running

regex.test(window.location.href)

which will return true if the regex is matched. So you'll end up with:

if (/\/folder1\/?$/i.test(window.location.href)) {
  document.getElementById("contactinfo").style.display="none";
} else {
  document.getElementById("contactinfo").style.display="block";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.