Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

javascript - comparing 2 strings alphabetically for sorting purposes

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You do say that the comparison is for sorting purposes. Then I suggest localeCompare instead:

"a".localeCompare("b");

It returns -1 since "a" < "b", 1 or 0 otherwise, like you need for Array.prototype.sort()

Keep in mind that sorting is locale dependent. E.g. in German, ? is a variant of a, so "?".localeCompare("b", "de-DE") returns -1. In Swedish, ? is one of the last letters in the alphabet, so "?".localeCompare("b", "se-SE") returns 1.

Without the second parameter to localeCompare, the browser's locale is used. Which in my experience is never what I want, because then it'll sort differently than the server, which has a fixed locale for all users.

Also, if what you are sorting contains numbers, you may want:

"a5b".localeCompare("a21b", undefined, { numeric: true })

This returns -1, recognizing that 5 as a number is less than 21. Without { numeric: true } it returns 1, since "2" sorts before "5". In many real-world applications, users expect "a5b" to come before "a21b".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...