简体   繁体   English

如何比较两个包含变音符号的UTF-8字符串

[英]How to compare two UTF-8 strings which contain diacritic characters

I want to add an element like this fiddle but I have a problem to compare my strings when a string has a UTF-8 character because "é" is > at all basics letters . 我想添加一个像小提琴这样的元素,但是当字符串具有UTF-8字符时,我很难比较我的字符串,因为"é" is > at all basics letters

<ol class="ingredientList">
    <li class="ingredient">Apples</li>
    <li class="ingredient">Carrots</li>
    <li class="ingredient">Clams</li>
    <li class="ingredient">Oysters</li>
    <li class="ingredient">Wheat</li>
</ol>
<ol class="ingredientList">
    <li class="ingredient">Barley</li>
    <li class="ingredient">éggs</li>
    <li class="ingredient">Millet</li>
    <li class="ingredient">Oranges</li>
    <li class="ingredient">Olives</li>
</ol>
$(".ingredient").click(function() {
    var element = $(this);
    var added = false;
    var targetList = $(this).parent().siblings(".ingredientList")[0];
    $(this).fadeOut("fast", function() {
        $(".ingredient", targetList).each(function() {
            if ($(this).text() > $(element).text()) {
                $(element).insertBefore($(this)).fadeIn("fast");
                added = true;
                return false;
            }
        });
        if (!added) $(element).appendTo($(targetList)).fadeIn("fast");
    });
});

Do you have any solutions to fix that ? 您有解决方案吗?

You can use the localeCompare() method to sort text which contains diacritics. 您可以使用localeCompare()方法对包含变音符号的文本进行排序。 Try this: 尝试这个:

$(".ingredient").click(function() {
    var $element = $(this);
    var $targetList = $element.closest('.ingredientList').siblings().first();

    $element.fadeOut("fast", function() {
        $element.appendTo($targetList);    
        $(".ingredient", $targetList).sort(function(a, b) {
            return $(a).text().localeCompare($(b).text());
        }).appendTo($targetList);
        $element.fadeIn('fast');
    });
});

Updated fiddle 更新的小提琴

Note that I amended your logic to make the selectors more efficient, and also to enable the sort algorithm. 请注意,我修改了您的逻辑,以使选择器更加有效,并启用了排序算法。

localeCompare MDN documentation 比较MDN文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM