Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison returns false. Strange javascript behaviour with jQuery mobile

I started to create a todo list with jQuery mobile in order to learn it better. I'm listening to the events coming from the buttons of a menu like this:

        me.selectedTarget = me.menuNode.find(".ui-btn").first();

        me.menuNode.on("click", ".ui-btn", function (e) {
            var target =  $(e.currentTarget)
                ,targetText = target.text();
            console.debug("Click on'", targetText,"'" );
            if(target === me.selectedTarget) return;

            if(targetText == "View To Do "){
                core.pub("view:todo");
            } else if(targetText == "View Done ") {
                core.pub("view:done");
            } else {
                me.selectedTarget.click();
            }
            me.selectedTarget = target;
        });

The variable targetText has one extra " " space at the end for some reason. I have 3 buttons, but the third one is a bit special - not relevant anyway -.

the buttons that this code listens to.

My problem is that I'm always getting on the last else clause. targetText never get's to be equal to "View To Do " or "View Done ".

Why isn't "View Done " == "View Done "? ~X(

firebug debugging results

the html markup

like image 997
Vlad Nicula Avatar asked Apr 14 '12 15:04

Vlad Nicula


1 Answers

The comparison is failing because the strings are not the same. So the question really is why are they not the same? Apparently the space in one of the strings is not the standard space character (Unicode has more than one space), or one of the strings has an invisible character in it (Unicode has those, too).

So to find out what's going on, I'd do this:

var index;
for (index = 0; index < targetText.length; ++index) {
    console.log("char " + index + ": " + targetText.charCodeAt(index));
}

...and the same with your string literal in your code (not retyping it, but moving it into a local and then outputting that; since if you retype it, you'll presumably type the normal space). Compare the sequences of character codes and you'll find the discrepancy.

like image 163
T.J. Crowder Avatar answered Nov 15 '22 00:11

T.J. Crowder