user381800
user381800

Reputation:

JavaScript Condition Matching but Not Returning True?

Please have a look at the following:

jQuery(document).ready(function() { 
    var full_url = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;    
    var part_url = window.location.protocol + "//" + window.location.host + "/domain/shop/";    
    part_url = part_url + "cat1/";

    if (full_url == part_url)
    {
        jQuery("li.cat1").addClass("current");  
    }    
});

For some reason the above code never becomes true and I am puzzled as why. I have individually alerted out the variable "part_url" and "full_url" and they both matched so why is the if statement not returning true? I know it's probably something silly that I've missed...

Upvotes: 0

Views: 432

Answers (3)

bobince
bobince

Reputation: 536755

window.location.host + "/" + window.location.pathname; 

location.pathname includes the leading /, so you'll be creating http://www.example.com//domain/shop/cat1 with two slashes after the hostname. Clearly this will never match. Refine your squinting-at-strings-to-see-if-they're-the-same powers!

Upvotes: 0

just somebody
just somebody

Reputation: 19257

if the equality operator says false, then they're not the same no matter how much you believe it. ;) try this:

var test = function (s, t)
{
    var sl = s.length;
    var tl = t.length;
    var l  = sl < tl ? sl : tl;
    for (var i = 0; i < l && s[i] == t[i]; ++i) /* empty */;
    if (i < l || sl != tl) {
        print("common head: '" + s.substr(0, i) + "'");
        print("tail s: '" + s.substr(i) + "'");
        print("tail t: '" + t.substr(i) + "'");
    }
};

Upvotes: 0

psmears
psmears

Reputation: 28110

Are you sure it's not returning true? Try:

alert(full_url == part_url);

That will give some indication as to whether the strings don't match, or whether the content of the if is just having no effect.

If it's a lower/upper case issue, then it's better to use toLowerCase() to compare, rather than regular expressions, as otherwise you can get errors / false matches (if the URLs contain regexp characters):

if (full_url.toLowerCase() == part_url.toLowerCase()) { ... }

If that's not it - try:

  • checking the lengths of the strings:

    alert(full_url.length); alert(part_url.length);
    
  • using substr on the strings to narrow down the part that doesn't match:

    alert(full_url.substr(1,20) == part_url(substr(1,20));
    

    (maybe even use a loop to compare character by character - it may be something like number '1' versus letter 'l'...)

Upvotes: 1

Related Questions