This is extracted from the much larger post: The Complete Guide to Working With Strings in Modern JavaScript
Equality
When you know you are comparing two string primitives, you can use either the ==
or ===
operators:
"abba" === "abba" // true
"abba" == "abba" // true
If you are comparing a string primitive to something that is not a string, ==
and ===
behave differently.
When using the ==
operator, the non-string will be coerced to a string. That means that JavaScript will try and make
it a string before comparing the values.
9 == "9"
// becomes
"9" == "9" //true
For a strict comparison, where non-strings are not coerced to strings, use ===
:
9 === "9" // false
The same is true of the not-equal operators, !=
and !==
:
9 != "9" // false
9 !== "9" // true
If you're not sure what to use, prefer strict equality using ====
.
When using String objects, two objects with the same value are not considered equal:
new String("js") == new String("js") // false new String("js") === new String("js") // false
Case sensitivity
For case-insensitive comparisons, do not convert both strings to upper or lowercase and then compare them, as this is unreliable with some characters.
Instead use localeCompare:
let a = 'Résumé';
let b = 'RESUME';
// Incorrect: returns 'false'
a.toLowerCase() === b.toLowerCase()
// Correct: returns '1'
a.localeCompare(b, undefined, { sensitivity: 'accent' })
localeCompare is supported in the following browsers
Greater/less than
When comparing strings using the <
and >
operators, JavaScript will compare each character in 'lexicographical order'.
That means that they are compared letter by letter, in the order they would appear in a dictionary:
"aardvark" < "animal" // true
"gamma" > "zulu" // false
When comparing strings using
<
>
, lowercase letters are considered larger than uppercase.
"aardvark" > "Animal" // true
This is because JavaScript is actually using each character's value in Unicode, where lowercase letters are after uppercase letters.
True or false strings
Empty strings in JavaScript are considered false when compared with the ==
operator
(but not when using ===
)
("" == false) // true
("" === false) // false
Strings with a value are 'true', so you can do things like this:
if (someString) {
// string has a value
} else {
// string is empty or undefined
}
Top comments (0)