ChatGPT解决这个技术问题 Extra ChatGPT

What is the correct way to check for string equality in JavaScript?

What is the correct way to check for equality between Strings in JavaScript?

Is there a reason not to use == ?
@Kendrick -- sure. It's type-coercion system can be incredibly unintuitive and can make errors very easy to overlook (it looks right, but can be very wrong)
@Kendrick - because {} == "[object Object]" evaluates to true, for example.
somewhat annoying that String().equals() is not a method in JS...
@AlexanderMills Why?

S
STW

always Until you fully understand the differences and implications of using the == and === operators, use the === operator since it will save you from obscure (non-obvious) bugs and WTFs. The "regular" == operator can have very unexpected results due to the type-coercion internally, so using === is always the recommended approach.

For insight into this, and other "good vs. bad" parts of Javascript read up on Mr. Douglas Crockford and his work. There's a great Google Tech Talk where he summarizes lots of good info: http://www.youtube.com/watch?v=hQVTIJBZook

Update:

The You Don't Know JS series by Kyle Simpson is excellent (and free to read online). The series goes into the commonly misunderstood areas of the language and explains the "bad parts" that Crockford suggests you avoid. By understanding them you can make proper use of them and avoid the pitfalls.

The "Up & Going" book includes a section on Equality, with this specific summary of when to use the loose (==) vs strict (===) operators:

To boil down a whole lot of details to a few simple takeaways, and help you know whether to use == or === in various situations, here are my simple rules: If either value (aka side) in a comparison could be the true or false value, avoid == and use ===. If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===. In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

I still recommend Crockford's talk for developers who don't want to invest the time to really understand Javascript—it's good advice for a developer who only occasionally works in Javascript.


It's not necessary when you're sure both operands are string, e.g., when using if (typeof foo == "string")
@Marcel -- you're correct, but it's much better to always use the === operator and never have to worry about the "am I really, totally, 100% certain that == will behave how I think it will?"
@STW – one example why Crockford is not the alpha and omega of JavaScript, is his advice not to use unary increment/decrement (++/--).
And never use ++ or -- or single line if/else statements or continue or the new operator or any other number of perfectly legitimate code practices that Crockford has deemed "harmful". And of course never ever even consider thinking about using eval or with even if their pitfalls are well understood. And have you seen the next version of JS? Stricter syntax and a handful of helper functions, some which have been floating around for years, is about all we get after all this time. The syntax has not evolved at all. If Crockford is behind this, then it has been a bad thing.
@CoffeeAddict -- a quick test in JSFiddle appears to disagree. They are both case-sensitive: jsfiddle.net/st2EU
A
Anurag

If you know they are strings, then there's no need to check for type.

"a" == "b"

However, note that string objects will not be equal.

new String("a") == new String("a")

will return false.

Call the valueOf() method to convert it to a primitive for String objects,

new String("a").valueOf() == new String("a").valueOf()

will return true


thank for that JSS, two string objects will never be equal unless they are the same object regardless of the value.
@JSS: Additionally, new String("a") == "a" is true (but wouldn't be with ===), because the left hand side will be converted into a primitive string value.
@JSS: new String("a") == new String("a"), new String("a") === new String("b"), new String("a") === new String("a") will all return false, since you're dealing with references to objects of the String class, not primitives of type string.
Just to clarify this for anyone reading it. new String(foo) creates a string object, and String(foo) converts foo to a string primitive.
@FakeRainBrigand - clear as mud, but that's what javascripts about, isn't it?
a
akelec

Just one addition to answers: If all these methods return false, even if strings seem to be equal, it is possible that there is a whitespace to the left and or right of one string. So, just put a .trim() at the end of strings before comparing:

if(s1.trim() === s2.trim())
{
    // your code
}

I have lost hours trying to figure out what is wrong. Hope this will help to someone!


Thanks a lot. It is strange to me though, because I made sure there was no whitespace to the left or right and still this was the only way to solve my problem. Maybe it is related to the internal representation of a string?
Thanks @akelec!! @Niko, it was likely due to the Zero-Width-Space character which is invisible to the naked eye. See en.wikipedia.org/wiki/Zero-width_space. Even though this character has its purposes, many developers resent its existence!
Thank you that was frustrating since the equality check in my if was failing yet I saw no whitespace when inspecting while debugging.
A common problem when loading a variable from a text file (i.e: using fetch). Thanks a lot.
This is the best answer.
K
Kamil Kiełczewski

You can use == or === but last one works in more simple way (src)

a == b (and its negation !=)

https://i.stack.imgur.com/nkpj6.png

a === b (and its negation !==)

https://i.stack.imgur.com/DIqvq.png


well at least '==' is symmetrical ... |-=)
@Lars not exactly: if("0"==0 && 0==[]) console.log("0"==[]);
I ment if a==b then b==a for all a and b
@Lars it is symmetrical like you say but... it's JS :P
B
Basheer AL-MOMANI

what led me to this question is the padding and white-spaces

check my case

 if (title === "LastName")
      doSomething();

and title was " LastName"

https://i.stack.imgur.com/XCo3c.png

so maybe you have to use trim function like this

var title = $(this).text().trim();

Thanks same here I used .toString().trim() in Typescript
A
Abhishek

There are actually two ways in which strings can be made in javascript.

var str = 'Javascript'; This creates a primitive string value. var obj = new String('Javascript'); This creates a wrapper object of type String. typeof str // string typeof obj // object

So the best way to check for equality is using the === operator because it checks value as well as type of both operands.

If you want to check for equality between two objects then using String.prototype.valueOf is the correct way.

new String('javascript').valueOf() == new String('javascript').valueOf()

D
Dunc

String Objects can be checked using JSON.stringify() trick.

var me = new String("me"); var you = new String("me"); var isEquel = JSON.stringify(me) === JSON.stringify(you); console.log(isEquel);


You are kidding right? Did you meant iSequel ;) Just kidding...
H
HoldOffHunger

Strict Comparisons

To do simple comparison, use === to check for strict equality. As others stated, this has the advantages of being most efficient and reducing the chances of buggy or uncertain code. Source: MDN Web Docs: Strict Equality.

var a = "hello1"; var b = "hello2"; console.log("a === a?" + (a === a) + "|"); console.log("a === b?" + (a === b) + "|");

Alphabetical Comparisons

If you want to compare two strings to know if a string comes before or after another string, based on natural sorting, use the <, >, <=, and >= operators. Source: MDN WebDocs for <, >, <=, and >=.

var a = "hello1"; var b = "hello2"; console.log("a < a?" + (a < a) + "|"); console.log("a < b?" + (a < b) + "|"); console.log("a > b?" + (a > b) + "|"); console.log("b > a?" + (b > a) + "|");


N
Nagibaba

Considering that both strings may be very large, there are 2 main approaches bitwise search and localeCompare

I recommed this function

function compareLargeStrings(a,b){
    if (a.length !== b.length) {
         return false;
    }
    return a.localeCompare(b) === 0;
}

g
grssnbchr

Also consider that ["foo", "bar"] == "foo,bar".