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?

1
  • Either remove the +1 or put the plus 1 outside the lastIndexOf brackets and change compare string. Commented Sep 7, 2016 at 8:08

3 Answers 3

2

@MattE simply update your code

document.documentURI.substr(url.lastIndexOf("/")) == "/colleagues"
Sign up to request clarification or add additional context in comments.

1 Comment

@MattE Welcome :-)
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

2 Comments

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 :-)
No problem. I found this post in stackoverflow, in order to answer your question "Is it possibly easier to use a regex?" stackoverflow.com/questions/273789/…
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

1 Comment

this also works thanks, appreciate the advice on troubleshooting :-)

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.