What is the correct way to check for equality between Strings in JavaScript?
asked Aug 27, 2010 at 17:37
8
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: //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
orfalse
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.
answered Aug 27, 2010 at 17:39
STWSTW
43.6k17 gold badges106 silver badges157 bronze badges
18
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
answered Aug 27, 2010 at 17:40
AnuragAnurag
138k36 gold badges219 silver badges257 bronze badges
6
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!
answered May 2, 2017 at 13:41
akelecakelec
3,5293 gold badges40 silver badges38 bronze badges
8
You can use ==
or ===
but last one works in more simple way [src]
a == b [and its negation !=]
a === b [and its negation !==]
answered Aug 3, 2020 at 19:44
Kamil KiełczewskiKamil Kiełczewski
75.5k26 gold badges335 silver badges311 bronze badges
5
what led me to this question
is the padding
and white-spaces
check my case
if [title === "LastName"]
doSomething[];
and title was " LastName"
so maybe you have to use
trim
function like this
var title = $[this].text[].trim[];
answered Jul 27, 2016 at 10:52
1
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 typeString
.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[]
answered May 2, 2015 at 19:11
AbhishekAbhishek
1,1961 gold badge8 silver badges12 bronze badges
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];
Dunc
17.7k6 gold badges82 silver badges99 bronze badges
answered Jul 4, 2018 at 12:33
Muhammad UsmanMuhammad Usman
7951 gold badge10 silver badges18 bronze badges
1
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 ,
=
operators. Source: MDN WebDocs for ,
=
.
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] + "|"];
answered May 26, 2021 at 15:47
HoldOffHungerHoldOffHunger
16.7k8 gold badges92 silver badges121 bronze badges
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;
}
answered Feb 25, 2020 at 10:25
NagibabaNagibaba
3,3341 gold badge31 silver badges38 bronze badges
Also consider that ["foo", "bar"] == "foo,bar"
.
answered Apr 19 at 20:09
grssnbchrgrssnbchr
2,8256 gold badges35 silver badges69 bronze badges
For strings, we have a supported method localCompare
which is very handy in string comparison. IMO, we should just use it and doesn't need to complicate stuff.
Usage:
const a = 'Hello'
const b = 'Hell'
a.localCompare[a] // 0
a.localCompare[b] // 1
b.localCompare[a] // -1
answered Aug 7 at 8:17