Gerico
Gerico

Reputation: 5169

jquery if anything in URL after specific page

I am looking to hide some items on a system where I have no control over the HTML.

I want to valid if there is anything after the url on the page of /jobs/. So for /jobs/ my function doesn't fire, the moment it becomes /jobs/XXXX then the function would fire.

I've tried this but I've no idea what it's actually doing as it validates on both /jobs/ and /jobs/xxx

if(window.location.href.indexOf("jobs") != -1) {
   alert("your url contains the word jobs");
}

Upvotes: 0

Views: 179

Answers (2)

Patel
Patel

Reputation: 1478

I assume you are only interested in the fact if URL ends with 'jobs/' or not. This is what you can do to check if it ends with 'jobs/' or not :

var str = window.location.href;

if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

if(str.endsWith('jobs/'))
  console.log("Yes!"); //Do things here
else
  console.log("Nope"); // or here..

Upvotes: 0

AmmarCSE
AmmarCSE

Reputation: 30557

You can use a regex to detect if it explicitly ends in /jobs/ with $

if((new RegExp('\/jobs\/$')).test(window.location.href)){
}

The reason

if(window.location.href.indexOf("jobs") != -1) {
   alert("your url contains the word jobs");
}

was working regardless of whether it ended in /jobs/ or not is because indexOf() checks that jobs exists anywhere in the string

Upvotes: 2

Related Questions