Coder Perfect

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

Problem

In JavaScript, what is the proper technique to check for equality between Strings?

Asked by JSS

Solution #1

always Use the === operator until you fully understand the distinctions and ramifications of the == and === operators. It will save you from esoteric (non-obvious) problems and WTFs. Because the intrinsic type-coercion of the “regular” == operator can produce unexpected results, employing === is always advised.

Read Mr. Douglas Crockford’s work for further information on this and other “good vs. poor” aspects of Javascript. He outlines a lot of useful information in a terrific Google Tech Talk: http://www.youtube.com/watch?v=hQVTIJBZook

Update:

Kyle Simpson’s You Don’t Know JS series is fantastic (and free to read online). The series delves into aspects of the language that are frequently misunderstood, as well as the “bad bits” that Crockford advises you to avoid. You can make effective use of them and avoid the risks if you understand them.

A section on Equality is included in the “Up & Going” book, with the following overview of when to employ the loose (==) vs strict (===) operators:

Crockford’s talk is still recommended for developers who don’t want to devote the time to truly learn Javascript—also it’s solid advise for a developer who just works with Javascript on occasion.

Answered by STW

Solution #2

There’s no need to check for type if you already know they’re strings.

"a" == "b"

String objects, on the other hand, will not be equal.

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

will return false.

To convert it to a primitive for String objects, use the function valueOf() { [native code] }() method.

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

will return true

Answered by Anurag

Solution #3

Just one thing to add to the answers: if all of these techniques return false, even if the strings appear to be equal, it’s conceivable that one of the strings has whitespace to the left or right of it. So, before comparing strings, just add a.trim() to the end:

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

I’ve wasted a lot of time trying to figure out what’s wrong. I hope this is of assistance to someone!

Answered by akelec

Solution #4

You can use == or ===, but the latter is more straightforward (src)

a == b (and its inverse,!=)

=== b (and its inverse,!==)

Answered by Kamil Kiełczewski

Solution #5

The padding and white-spaces are what prompted me to ask this question.

check my case

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

“LastName” was the name of the character.

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

Answered by Basheer AL-MOMANI

Post is based on https://stackoverflow.com/questions/3586775/what-is-the-correct-way-to-check-for-string-equality-in-javascript