Convert Javascript UTF-8 to ASCII (like Iconv('UTF-8', 'ASCII//TRANSLIT', $string) in PHP)

前端 未结 3 489
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 04:09

I\'m wondering how it\'s possible to \'translate\' characters in UTF-8 to the closest ASCII equivalent using Javascript, just like Iconv doest in PHP.

Example:

ü

相关标签:
3条回答
  • 2021-02-08 04:40

    The easiest way I've found:

    var str = "üó";
    var combining = /[\u0300-\u036F]/g; 
    
    console.log(str.normalize('NFKD').replace(combining, ''));
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize

    0 讨论(0)
  • 2021-02-08 04:44

    There is now a port of iconv to JS: https://www.npmjs.com/package/iconv

    var iconv = new Iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE');
    iconv.convert('ça va が'); // "ca va "
    
    0 讨论(0)
  • 2021-02-08 04:49

    As @Pointy said, your only option is to map/replace characters according to a dictionary.

    You'll find this really useful: https://github.com/backbone-paginator/backbone.paginator/blob/a579796a30e583c4dfa09e0a86e4abd21e0b5b56/plugins/diacritic.js

    0 讨论(0)
提交回复
热议问题