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
858 views
in Technique[技术] by (71.8m points)

jquery - How do you sort letters in JavaScript, with capital and lowercase letters combined?

I'm working on a JavaScript (jQuery's OK too if this needs it, but I doubt it will) function to alphabetize a string of letters. Let's say the string that I want to sort is: "ACBacb".

My code as of now is this:

var string='ACBacb';
alert(string.split('').sort().join(''));

This returns ABCabc. I can see why that happens, but that is not the format that I am looking for. Is there a way that I can sort it by putting the same letters next to each other, capital letter first? So when I put in ACBacb, I get AaBbCc?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Array.sort can have a sort function as optional argument.

What about sorting the string first (ACBacbA becomes AABCabc), and then sorting it case-insensitive:

function case_insensitive_comp(strA, strB) {
    return strA.toLowerCase().localeCompare(strB.toLowerCase());
}

var str = 'ACBacbA';
// split the string in chunks
str = str.split("");
// sorting
str = str.sort();
str = str.sort( case_insensitive_comp )
// concatenate the chunks in one string
str = str.join("");

alert(str);

As per Felix suggestion, the first sort function can be omitted and merged in the second one. First, do a case-insensitive comparison between both characters. If they are equal, check their case-sensitive equivalents. Return -1 or 1 for a difference and zero for equality.

function compare(strA, strB) {
   var icmp = strA.toLowerCase().localeCompare(strB.toLowerCase());
   if (icmp != 0) {
       // spotted a difference when considering the locale
       return icmp;
   }
   // no difference found when considering locale, let's see whether
   // capitalization matters
   if (strA > strB) {
       return 1;
   } else if (strA < strB) {
       return -1;
   } else {
       // the characters are equal.
       return 0;
   }
}
var str = 'ACBacbA';
str = str.split('');
str = str.sort( compare );
str = str.join('');

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

1.4m articles

1.4m replys

5 comments

57.0k users

...