I have the following script
document.write("12" < "2");
which returns true. Any reason why? The documentation says that javascript pares strings numerically but, I don't see how "12" is less than "2".
I have the following script
document.write("12" < "2");
which returns true. Any reason why? The documentation says that javascript pares strings numerically but, I don't see how "12" is less than "2".
"Strings are pared based on standard lexicographical ordering, using Unicode values."
That means that '12' < '2'
just like 'a2' < 'b'
.
– Paul
Commented
Jun 5, 2013 at 22:46
JavaScript pares strings character by character until one of the characters is different.
1 is less than 2 so it stops paring after the first character.
I believe it is doing a lexicographic parison - the first char in string one is '1', which is less than the first char of string two, which is '2'. More about Lexicographic order here: http://en.wikipedia/wiki/Lexicographical_order
This is because the first character of "12"
is 1
, which es before "2"
; and JavaScript string parison is lexically/alphabetically, rather than numerically. Though it appears partially numeric, since 1
is sorted ahead of 2
.
You can, however, simply pare the numbers as numbers:
document.write(parseFloat("12") < parseFloat("2"));
Try:
document.write(parseInt("12") < parseInt("2"));