Remove accents/diacritics in a string in JavaScript

前端 未结 29 2380
轻奢々
轻奢々 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:56

    There's a lot out there, but I think this one is simple and good enough:

     function remove_accents(strAccents) {
        var strAccents = strAccents.split('');
        var strAccentsOut = new Array();
        var strAccentsLen = strAccents.length;
        var accents =    "ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž";
        var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
        for (var y = 0; y < strAccentsLen; y++) {
            if (accents.indexOf(strAccents[y]) != -1) {
                strAccentsOut[y] = accentsOut.substr(accents.indexOf(strAccents[y]), 1);
            } else
                strAccentsOut[y] = strAccents[y];
        }
        strAccentsOut = strAccentsOut.join('');
    
        return strAccentsOut;
    }
    

    If you also want to remove special characters and transform spaces and hyphens in underscores, do this:

    string = remove_accents(string);
    string = string.replace(/[^a-z0-9\s]/gi, '').replace(/[-\s]/g, '_');
    

提交回复
热议问题