将 Javascript UTF-8 转换为 ASCII(如 PHP 中的 Icon('UTF-8', 'ASCII//TRANSLIT', $string))

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13309620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:23:06  来源:igfitidea点击:

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

javascriptutf-8asciiiconv

提问by Simon

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.

我想知道如何使用 Javascript 将 UTF-8 中的字符“翻译”为最接近的 ASCII 等价物,就像 PHP 中的 Iconv 那样。

Example:

例子:

ü becomes u
ó becomes o

ü 变成 u
ó 变成 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.

我宁愿不使用替换,因为 a) 它需要一组完整的字符,这是很多工作 b) 我很难获得一组完整的字符,而且我永远不会确定如果我错过了一两个。

采纳答案by alexandernst

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

正如@Pointy 所说,您唯一的选择是根据字典映射/替换字符。

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

你会发现这真的很有用:https: //github.com/backbone-paginator/backbone.paginator/blob/a579796a30e583c4dfa09e0a86e4abd21e0b5b56/plugins/diacritic.js

回答by Rez

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://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize