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('');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…