[英]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. 我正在研究一个JavaScript(jQuery也可以,如果它需要它,但我怀疑它会)用于按字母顺序排列一串字母。 Let's say the string that I want to sort is: "ACBacb". 假设我要排序的字符串是:“ACBacb”。
My code as of now is this: 我现在的代码是这样的:
var string='ACBacb';
alert(string.split('').sort().join(''));
This returns ABCabc. 这将返回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? 所以当我输入ACBacb时,我得到了AaBbCc?
Array.sort
can have a sort function as optional argument. Array.sort
可以将sort函数作为可选参数。
What about sorting the string first (ACBacbA becomes AABCabc), and then sorting it case-insensitive: 首先对字符串进行排序(ACBacbA变为AABCabc),然后将其排序为不区分大小写:
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. 根据Felix的建议,第一个排序函数可以省略并合并到第二个排序函数中。 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. 返回-1或1表示差异,返回0表示相等。
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('');
You can pass a custom comparison function to Array.sort()
您可以将自定义比较函数传递给Array.sort()
The already given answers are right so far that you have to use a custom comparison function. 到目前为止,已经给出的答案是正确的,你必须使用自定义比较功能。 However you have to add an extra step to sort capital letters before lower case once: 但是,您必须在小写一次之前添加一个额外的步骤来对大写字母进行排序:
function cmp(x,y) {
if(x.toLowerCase() !== y.toLowerCase()) {
x = x.toLowerCase();
y = y.toLowerCase();
}
return x > y ? 1 : (x < y ? -1 : 0);
// or return x.localeCompare(y);
}
If the letters are the same, the originals have to be compared, not the lower case versions. 如果字母相同,则必须比较原件,而不是小写版本。 The upper case letter is always "larger" than the lower case version. 大写字母总是比小写字母“大”。
DEMO (based on @Matt Ball 's version) DEMO (基于@Matt Ball的版本)
a working example http://jsfiddle.net/uGwZ3/ 一个工作示例http://jsfiddle.net/uGwZ3/
var string='ACBacb';
alert(string.split('').sort(caseInsensitiveSort).join(''));
function caseInsensitiveSort(a, b)
{
var ret = 0;
a = a.toLowerCase();b = b.toLowerCase();
if(a > b)
ret = 1;
if(a < b)
ret = -1;
return ret;
}
basic example for another replace, combined with lowercase :D 另一个替换的基本示例,结合小写:D
<button onclick="myFunction('U')">Try it</button> <p id="demo"></p> <script> function myFunction(val) { var str = "HELLO WORLD!"; var res = str.toLowerCase().split("o"); var elem = document.getElementById("demo").innerHTML for(i = 0; i < res.length; i++){ (i > 0)?elem += val + res[i]:elem += res[i]; } } </script>
Use a custom sort function like this: 使用这样的自定义排序函数:
function customSortfunc(a,b){
var lca = a.toLowerCase(), lcb = b.toLowerCase();
return lca > lcb ? 1 : lca < lcb ? -1 : 0;
}
var string='ACBacb';
alert(string.split('').sort(customSortfunc).join(''));
You can read more about the sort function here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort 您可以在此处阅读有关sort函数的更多信息: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
Beware : if you use localeCompare
like other answer suggests "u" and "ü" will be sorted together as the same letter, since it disregards all diacritics. 注意 :如果你使用localeCompare
像其他答案所示,“u”和“ü”将作为同一个字母排序在一起,因为它忽略了所有的变音符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.