Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript String Compare == sometimes fails

How could the following code sometimes evaluate to false?

(transport.responseText == '1' || 
 transport.responseText == 'CARD_VALID')

My JavaScript code:

if (transport.responseText == '1' || 
    transport.responseText == 'CARD_VALID') {
    // do something.
}
else if (transport.responseText == 'CARD_INVALID' || 
             transport.responseText == 'INVALID_CHECKSUM') {
    // do something else....
}
else {
    new Ajax.Request('/report_error.php?responseText='+transport.responseText);
    // report error to user
}

What could cause JavaScript string compare == to return false when the strings are identical?

like image 923
chaimp Avatar asked May 14 '09 14:05

chaimp


People also ask

Can we use == to compare strings in JavaScript?

In JavaScript, strings can be compared based on their “value”, “characters case”, “length”, or “alphabetically” order: To compare strings based on their values and characters case, use the “Strict Equality Operator (===)”.

Can you use == when comparing strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

When comparing strings Why is == not a good idea?

Using the “==” operator for comparing text values is one of the most common mistakes Java beginners make. This is incorrect because “==” only checks the referential equality of two Strings, meaning if they reference the same object or not.

Is it safe to compare JavaScript strings?

Firstly, you are safe to compare strings that contain characters from Basic Multilangual Plane (including the ASCII characters) using regular comparison operators === , == or utility function Object.is() . Both str1 and str2 contain ASCII characters, so you can safely compare them using comparison operators.


8 Answers

Double equals is the appropriate way to compare strings in Javascript, it is returning false then there may be whitespace to the left and or right of one string.

Put a .trim() on the end of the strings and my comparison should started working:

var panel = response.substr(0, response.indexOf("<")).trim();
if(panel == "combo"){
    //do something
}
like image 80
Jacob Avatar answered Sep 25 '22 19:09

Jacob


I had a similar problem where two obviously identical strings would not be equal, and I was pulling my hair out trying to solve it, so I did this:

for (var c=0; c<string_1.length; c++) {
    if (string_1.charCodeAt(c) != string_2.charCodeAt(c)) {
        alert('c:'+c+' '+string_1.charCodeAt(c)+'!='+string_2.charCodeAt(c));
        valid = false;
    }
}

And I found that the last character on one string was 10, and the last character on the other was 13, I thought both strings were null terminated, but they were not.

like image 39
Robert Avatar answered Sep 27 '22 19:09

Robert


A1 = "speed"
A2 = "speed" 

if(A1 == A2)  => Error !!!

USE THIS TEST IN CONSOLE:

escape("speed")

result: "speed"

escape(A1)

result: "speed%0D" => This is the problem %0D !!!

escape(A2)

result: "speed" => OK !!!

Use correct code:

if(A1.slice(0, -1) == A2) This is OK!
like image 23
Lightlion Avatar answered Sep 24 '22 19:09

Lightlion


I had the same problem and i noticed that i was comparing two objects

enter image description here

to solve this issue i had to use

JSON.stringify(user._id) === JSON.stringify(userId) // true 
like image 26
Ahmed Younes Avatar answered Sep 27 '22 19:09

Ahmed Younes


Try using === to match exactly (type and value). This is the recommended comparison operator in javascript.

Check the datatypes of the strings to make sure, and look for hidden unicode or control characters in both strings.

like image 21
sat Avatar answered Sep 27 '22 19:09

sat


If you want something a little less complicated and you are dealing with NUMERIC VALUES, use

parseFloat()

works like a charm

like image 33
Jamisco Avatar answered Sep 28 '22 19:09

Jamisco


I would advice you to use normalization preferably "NFKC" or "NFKD" as these seem to normalize non-breaking space into regular space.

So you can write your code as :-

string1.normalize("NFKC") === string2.normalize("NFKC")
like image 27
Yatharth Varshney Avatar answered Sep 26 '22 19:09

Yatharth Varshney


Try capturing the value of responseText into a different variable before entering that code block, in case the variable is updated somewhere in there.

I don't have that much experience directly using XmlHttpRequest, but I do know that javascript has a number of places where it uses volatile references to interface objects that can change during execution, rather than a simple value.

like image 32
Joel Coehoorn Avatar answered Sep 26 '22 19:09

Joel Coehoorn