我正在尝试编写一个函数,它接受任何包含unicode pseduo字母表中的字符的字符串,并返回一个等价的字符串,其中这些字符已被ASCII中的常规字符替换。
const toRegularCharacters = s => {
// ?
};
toRegularCharacters('ⓗⓔⓛⓛⓞ, ⓦⓞⓡⓛⓓ'); // "hello, world"
toRegularCharacters(', '); // "hello, world"
toRegularCharacters('ん乇レレo, wo尺レd'); // "hello, world"我不想自己写张查表。我看过各种"slugify“库,但它们只删除重音等等。理想情况下,该函数应该在Node和浏览器中工作。
当然,并不是每个特殊的角色都会有一个固定的等价物。在这些情况下,解决方案应该进行合理的猜测(例如,"尺" -> "R")。对于具有“真转换”的伪字母表,它应该完美地工作:
当前的真实变换:圆圈、负圈、亚洲全宽、数学粗体、数学粗体、数学大胆斜体、数学粗体脚本、数学双击、数学单空格、数学无符号、数学无衬线粗体、数学无衬线粗体斜体、数学无衬线斜体、数学无衬线斜体、带括号、区域指示符号、平方、负平方和标记文本(隐藏元数据标记不可见)。
我该怎么做?
从“常规”字符串到伪字母表字符串在这里实现:https://qaz.wtf/u/convert.cgi?text=hello%2C+world
发布于 2020-01-06 15:52:09
根据这个答案的建议,该解决方案使用unicode-12.1.0 NPM包:
const unicodeNames = require('unicode-12.1.0/Names');
const overrides = Object.freeze({
'ん': 'h',
'乇': 'E',
'レ': 'l',
'尺': 'r',
// ...
});
const toRegularCharacters = xs => {
if (typeof xs !== 'string') {
throw new TypeError('xs must be a string');
}
return [ ...xs ].map(x => {
const override = overrides[x];
if (override) {
return override;
}
const names = unicodeNames
.get(x.codePointAt(0))
.split(/\s+/);
// console.log({
// x,
// names,
// });
const isCapital = names.some(x => x == 'CAPITAL');
const isLetter = isCapital || names.some(x => x == 'SMALL');
if (isLetter) {
// e.g. "Ŧ" is named "LATIN CAPITAL LETTER T WITH STROKE"
const c = names.some(x => x == 'WITH') ?
names[names.length - 3] :
names[names.length - 1];
return isCapital ?
c :
c.toLowerCase();
}
return x;
}).join('');
};
console.log(
toRegularCharacters('..')
);
console.log(
toRegularCharacters('-')
);
console.log(
toRegularCharacters('ん乇レレo, wo尺レd')
);
console.log(
toRegularCharacters('ŦɆSŦƗNǤ')
);Names数据表包含所需的信息,但不是最好的形式,因此需要进行一些黑客字符串操作才能将字符取出。
重写的映射用于'尺'这样的情况。
更好的解决方案是提取@Seth中提到的idn_mapping属性。
发布于 2020-01-06 14:54:13
您可以编写代码来查询Unicode数据库,您可以从Unicode财团下载该数据库(或者通过字符效用进行查询,但这可能是有限的)。该数据库包含的东西,如什么符号是“混淆”,为其他符号。
例如,您的from,is U+1D4F1,它有lots of confusables,其中之一当然是标准的拉丁文小写h (U+0068)。因此,您可以遍历输入字符串中的每个字符,查找它,如果它有一个拉丁文as可混淆(可能也是0-9 ),用它替换它。
不会是完美的。正如deceze所指出的那样,ん没有列出任何混淆的内容,即使在英语读者看来它确实有点像"h“。H型也是如此。因此,您可能需要补充您自己的查找,即使您已经说过您不想(或只是生活在不完美)。
https://stackoverflow.com/questions/59613915
复制相似问题