MattE
MattE

Reputation: 159

How to match url in javascript using lastIndexOf?

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?

Upvotes: 0

Views: 444

Answers (3)

Ahmed Jehanzaib
Ahmed Jehanzaib

Reputation: 184

@MattE simply update your code

document.documentURI.substr(url.lastIndexOf("/")) == "/colleagues"

Upvotes: 2

a.szechlicki
a.szechlicki

Reputation: 66

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

Upvotes: 1

Mayday
Mayday

Reputation: 5136

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

Upvotes: 1

Related Questions