简体   繁体   中英

javascript checking for current url not working

I want to check if my current page URL is ending with this /something and if is ending with that, do something.

So, I've tried this:

if('http://'+location.hostname+location.pathname+'/something') {
  //do something;
}

here it validates every time even if I'm not on that specific URL .

Then, I've tried this:

if(location.pathname === "/something") {
  // Do Something
}

Here, I'm getting Undefined inside the console.

I understand that this means that I have an error in my code somewhere but I don't know where this error might be ?

How can I check where the error occurs ?

LATER UPDATE: I've tried every answer in the console and for each one I'm getting Undefined This is how my URL is looking website.com/parent/child/something . Inside the if statement I'm just trying to hide and element which exists on the page like this: jQuery(".class").hide(); This is so frustrating, It's definetly something wrong with the code.

使用window.location.href获取当前URL,或使用window.location.pathname仅获取路径

if(window.location.pathname=="yourvalue")

That's checks a last element of a url path.

if (window.location.pathname.split('/').pop() === "something") {
  //...
}
var url = "http://www.domain.com/first/second/something";
var url_ending = url.substring(url.lastIndexOf("/"), url.length);
if(url_ending == "something"){
    // Do something
}
 var url = window.location.href;
 var url_ending = url.substring(url.lastIndexOf("/"), url.length);
 if(url_ending == "something")
 {
     // Do something
 }
 else
 {
     //Do other things 
 }

 hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM