Remove accents/diacritics in a string in JavaScript

前端 未结 29 2381
轻奢々
轻奢々 2020-11-21 13:29

How do I remove accentuated characters from a string? Especially in IE6, I had something like this:

accentsTidy = function(s){
    var r=s.toLowerCase();
           


        
29条回答
  •  隐瞒了意图╮
    2020-11-21 13:59

    One solution that seems to be way faster by the given test : http://jsperf.com/diacritics/9

    function removeDiacritics(str) {
       return str.replace(/[^A-Za-z0-9\s]+/g, function(a){
          return diacriticsMap[a] || a; 
       });
    }
    removeDiacritics(teste);
    

    Working example: http://jsbin.com/sovorute/1/edit

    Reasoning: One reason this is much faster is because we only iterate through the special characters, picked by the negated regex pattern. The fastest of the tests (String Iteration without in) iterates 1001 on the given text, which means every character. This one iterates only 35 times and outputs the same result. Keep in mind that this will only replace what is indicated in the map.

    Classic article on the subject: http://alistapart.com/article/accent-folding-for-auto-complete

    Credit: http://semplicewebsites.com/removing-accents-javascript , also provides a nice character map.

提交回复
热议问题