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

为君一笑 提交于 2019-12-09 05:45:06

问题


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:

ü becomes u
ó becomes o

I'd rather not use a replace, because a) it requires a complete set of characters, which is a lot of work and b) i'd would be hard to get a complete set of characters, and i'll never be certain if i'm missing one or two.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/13309620/convert-javascript-utf-8-to-ascii-like-iconvutf-8-ascii-translit-strin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!