comparing 2 strings alphabetically for sorting purposes

javascript, jquery

Solution

Lets look at some test cases - try running the following expressions in your JS console:

"a" < "b"

"aa" < "ab"

"aaa" < "aab"

All return true.

JavaScript compares strings character by character and "a" comes before "b" in the alphabet - hence less than.

In your case it works like so -

1 . "a​aaa" < "​a​b"

compares the first two "a" characters - all equal, lets move to the next character.

2 . "a​a​​aa" < "a​b​​"

compares the second characters "a" against "b" - whoop! "a" comes before "b". Returns true.

Problem

I'm trying to compare 2 strings alphabetically for sorting purposes. For example I want to have a boolean check like `if('aaaa' < 'ab')`. I tried it, but it's not giving me correct results, so I guess that's not the right syntax. How do I do this in jquery or Javascript?

Original source

Related problems