DEV Community

Dave Saunders
Dave Saunders

Posted on • Updated on • Originally published at baseclass.io

Comparing strings in JavaScript

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

For a strict comparison, where non-strings are not coerced to strings, use ===:

9 === "9" // false
Enter fullscreen mode Exit fullscreen mode

The same is true of the not-equal operators, != and !==:

9 != "9" // false
9 !== "9" // true
Enter fullscreen mode Exit fullscreen mode

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' })
Enter fullscreen mode Exit fullscreen mode

localeCompare is supported in the following browsers

localeCompare browser support: Chrome 24+, Edge 12+, FireFox 29+, Safari 10+, Opera 15+


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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)