你如何在 JavaScript 中对字母进行排序,大写和小写字母组合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5285995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:28:47  来源:igfitidea点击:

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

javascriptjquery

提问by Zak

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".

我正在研究一个 JavaScript(如果需要,jQuery 也可以,但我怀疑它会)函数来按字母顺序排列一串字母。假设我要排序的字符串是:“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?

这将返回 ABCabc。我可以理解为什么会发生这种情况,但这不是我正在寻找的格式。有没有一种方法可以通过将相同的字母放在一起来排序,大写字母在前?所以当我输入 ACBacb 时,我得到 AaBbCc?

回答by Lekensteyn

Array.sortcan have a sort function as optional argument.

Array.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. 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.

根据 Felix 的建议,第一个排序函数可以省略并合并到第二个排序函数中。首先,在两个字符之间进行不区分大小写的比较。如果它们相等,请检查它们区分大小写的等效项。返回 -1 或 1 表示差异,零表示相等。

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('');

回答by Felix Kling

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)

演示(基于@Matt Ball的版本)

回答by EGL 2-101

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;
}

回答by Martin Jespersen

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

您可以在此处阅读有关排序功能的更多信息:https: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

Beware: if you use localeComparelike other answer suggests "u" and "ü" will be sorted together as the same letter, since it disregards all diacritics.

当心:如果您localeCompare像其他答案一样使用建议“u”和“ü”将作为同一个字母排序在一起,因为它忽略所有变音符号。

回答by Jiggly

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>