John Hoffman
John Hoffman

Reputation: 18607

What is the logic underlying javascript string comparisons?

Apparently, the below javascript prints TRUE.

var s = "hippo";
var t = "Hippo";
var test = (s > t);
document.write(test ? "TRUE" : "FALSE");​

What makes "hippo" greater than "Hippo"? The ASCII value for H is greater than the ASCII value of h.

What is the logic underlying javascript string comparisons?

http://jsfiddle.net/dUadG/1/

Upvotes: 1

Views: 141

Answers (2)

JayC
JayC

Reputation: 7141

In dictionary ordering, we generally want lowercase to come after uppercase so that proper names show up first. I suppose that doesn't have to be the case; that's just the convention for English speakers AFAIK. "X Greater than Y" in strings means "X shows up in a dictionary after Y". So this is not unexpected.

Upvotes: 1

user123444555621
user123444555621

Reputation: 152966

It's not ASCII, but UTF-16:

ECMAScript source text is represented as a sequence of characters in the Unicode character encoding, version 3.0 or later. The text is expected to have been normalised to Unicode Normalised Form C (canonical composition), as described in Unicode Technical Report #15. Conforming ECMAScript implementations are not required to perform any normalisation of text, or behave as though they were performing normalisation of text, themselves. ECMAScript source text is assumed to be a sequence of 16-bit code units for the purposes of this specification. Such a source text may include sequences of 16-bit code units that are not valid UTF-16 character encodings. If an actual source text is encoded in a form other than 16-bit code units it must be processed as if it was first convert to UTF-16.

http://es5.github.com/#x6

Also try:

'h'.charCodeAt(0);
'H'.charCodeAt(0);

Upvotes: 2

Related Questions