Advertisement
Advertisement


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


Question

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

2020/08/03
1
870
8/3/2020 7:45:09 PM


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

2010/08/27

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!

2018/04/06

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

check my case

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

and title was " LastName"

enter image description here

so maybe you have to use trim function like this

var title = $(this).text().trim();
2018/10/31

Unless you really know how coercion works, you should avoid == and use the identity operator === instead. But you should read this to understand how it works.

If you use ==, you let the language do some type coercion for you, so for example:

"1" == 1 // true
"0" == false // true
[] == false // true

As Douglas Crockford's said in his book:

It’s always better use the identity operator.

2016/01/26

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

  1. var str = 'Javascript'; This creates a primitive string value.

  2. 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()
2015/05/02

Source: https://stackoverflow.com/questions/3586775
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]