Adam A
Adam A

Reputation: 14618

For JS strings, is a.localeCompare(b) === 0 always the same as a === b?

Given two strings, does localeCompare always work the same as triple equals for equality comparison?

Chinese characters and astral characters seem ok

function compareEm(a,b) {
    if (a === b != a.localeCompare(b) === 0) {
        console.log(a, b, a === b, a.localeCompare(b))
    }
}

compareEm('\u6f22', "漢") // no output
compareEm('💩', "\uD83D\uDCA9") // no output

Is there a case where this doesn't hold true? If I change my locale, will it cease to hold true?

Upvotes: 3

Views: 534

Answers (1)

Paul Draper
Paul Draper

Reputation: 83253

a.localeCompare(b) === 0 is equivalent to a === b.

localeCompare only really becomes interesting when

  1. you start paying attention to the sign of the non-zero answers (e.g. 'á'.localeCompare('b'))

  2. or if you add flags, e.g. case-insensitivity.

FYI, localeCompare can be inconsistent among browsers for unequal strings.

Upvotes: 2

Related Questions