Efficiently replace all accented characters in a string?

后端 未结 21 2598
别跟我提以往
别跟我提以往 2020-11-22 04:35

For a poor man\'s implementation of near-collation-correct sorting on the client side I need a JavaScript function that does efficient single character rep

21条回答
  •  悲&欢浪女
    2020-11-22 05:25

    Based on the solution by Jason Bunting, here is what I use now.

    The whole thing is for the jQuery tablesorter plug-in: For (nearly correct) sorting of non-English tables with tablesorter plugin it is necessary to make use of a custom textExtraction function.

    This one:

    • translates the most common accented letters to unaccented ones (the list of supported letters is easily expandable)
    • changes dates in German format ('dd.mm.yyyy') to a recognized format ('yyyy-mm-dd')

    Be careful to save the JavaScript file in UTF-8 encoding or it won't work.

    // file encoding must be UTF-8!
    function getTextExtractor()
    {
      return (function() {
        var patternLetters = /[öäüÖÄÜáàâéèêúùûóòôÁÀÂÉÈÊÚÙÛÓÒÔß]/g;
        var patternDateDmy = /^(?:\D+)?(\d{1,2})\.(\d{1,2})\.(\d{2,4})$/;
        var lookupLetters = {
          "ä": "a", "ö": "o", "ü": "u",
          "Ä": "A", "Ö": "O", "Ü": "U",
          "á": "a", "à": "a", "â": "a",
          "é": "e", "è": "e", "ê": "e",
          "ú": "u", "ù": "u", "û": "u",
          "ó": "o", "ò": "o", "ô": "o",
          "Á": "A", "À": "A", "Â": "A",
          "É": "E", "È": "E", "Ê": "E",
          "Ú": "U", "Ù": "U", "Û": "U",
          "Ó": "O", "Ò": "O", "Ô": "O",
          "ß": "s"
        };
        var letterTranslator = function(match) { 
          return lookupLetters[match] || match;
        }
    
        return function(node) {
          var text = $.trim($(node).text());
          var date = text.match(patternDateDmy);
          if (date)
            return [date[3], date[2], date[1]].join("-");
          else
            return text.replace(patternLetters, letterTranslator);
        }
      })();
    }
    

    You can use it like this:

    $("table.sortable").tablesorter({ 
      textExtraction: getTextExtractor()
    }); 
    

提交回复
热议问题