0

I'm new to javascript but am trying to conditionally display a button/link on a page if it matches a certain url with the code below:

LinkNode = document.getElementById("csv");
var url = document.documentURI
  if(document.documentURI.substr(url.lastIndexOf("/"+1)) == "/colleagues"){
    LinkNode.style.visibility= "visible";
  }
  else{
    LinkNode.style.visibility= "hidden";
}

Can anyone advise what I am doing wrong or how to match my url ending in "/colleagues" because this isn't matching? Is it possibly easier to use a regex?

How might I test to see what document.documentURI.substr(url.lastIndexOf("/"+1)) is actually producing?

MattE
  • 159
  • 12

3 Answers3

2

@MattE simply update your code

document.documentURI.substr(url.lastIndexOf("/")) == "/colleagues"
Ahmed Jehanzaib
  • 158
  • 1
  • 10
1

If you don't need to be very accurate, you can just use it this way:

if (document.documentURI.indexOf("/colleagues") !== -1) {
  LinkNode.style.visibility= "visible";
}
else {
  LinkNode.style.visibility= "hidden";
}

NOTE

This will just find in your whole URI if "/colleagues" exist. This means, it won't find it in the domain, since it has the "/". But it might be that you have "www.domain.com/colleagues/sample" or "www.domain.com/sample/colleagues" and it will enter the if in both cases

Mayday
  • 4,680
  • 5
  • 24
  • 58
  • Thanks, this also works but in my case I will have 'colleagues' in other parts of the string on other pages and not want to display the link... However this is really useful to know :-) – MattE Sep 07 '16 at 08:19
  • No problem. I found this post in stackoverflow, in order to answer your question "Is it possibly easier to use a regex?" http://stackoverflow.com/questions/273789/is-there-a-version-of-javascripts-string-indexof-that-allows-for-regular-expr – Mayday Sep 07 '16 at 08:24
1

you can use a regex match:

var urlIndex = url.search("\/colleagues$");
if (urlIndex !== -1) {
  LinkNode.style.visibility= "visible";
} else {
  LinkNode.style.visibility= "hidden";
}

string.search method returns index of first match, or -1 if there is no match.

as for testing, you can use debugging tools that are available in almost every desktop browser, and set a breakpoint at a line you want to inspect other way is to add console.log('some text', someValue) and see output in browser console

a.szechlicki
  • 66
  • 1
  • 4