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

时间:2021-05-02 00:10:23

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?

5 个解决方案

#1


22  

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. 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表示差异,返回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('');

#2


5  

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的版本)

#3


1  

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

#4


0  

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”和“ü”将作为同一个字母排序在一起,因为它忽略了所有的变音符号。

#5


0  

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>

#1


22  

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. 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表示差异,返回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('');

#2


5  

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的版本)

#3


1  

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

#4


0  

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”和“ü”将作为同一个字母排序在一起,因为它忽略了所有的变音符号。

#5


0  

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>