John
John

Reputation: 4981

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.

<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 ?

Upvotes: 2

Views: 828

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337580

You can use the localeCompare() method to sort text which contains diacritics. 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

Upvotes: 6

xoxox
xoxox

Reputation: 798

For comparison, you may want to replace the accentuated characters: Remove accents/diacritics in a string in JavaScript

Upvotes: 0

Related Questions