如何比较出现相似字符但不同字符代码的字符串? [英] How to compare strings in which appears similar characters but different char codes?

查看:43
本文介绍了如何比较出现相似字符但不同字符代码的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在比较具有不同字符代码但类似字符的字符串时遇到问题,如下所示:

I have the problem with comparing strings with different char codes but similar characters like the following:

console.log('³' === '3') // false;

由于不同的字符代码,上面代码中的错误值:

False value from the code above because of different char codes:

console.log('³'.charCodeAt(0)) // 179
console.log('3'.charCodeAt(0)) // 51

将值转换为相等的通用解决方案是什么?我需要它,因为我需要比较所有数字,例如 1,2,3,4,5....

What is a universal solution to convert values to be equals? I need it because I need to compare all numbers like 1,2,3,4,5....

谢谢

推荐答案

看看 ASCII 折叠,它主要用于将重音字符转换为非重音字符.此处有一个 JS 库.

Look into ASCII folding, which is primarily used to convert accented characters to unaccented ones. There's a JS library for it here.

对于您提供的示例,它会起作用 - 对于其他示例,它可能不会.这取决于等价性的定义方式(只有你知道相似"是什么意思——不同的字符是不同的字符).

For your provided example, it will work - for other examples, it might not. It depends on how the equivalence is defined (nobody but you knows what you mean by "similar" - different characters are different characters).

如果您已经知道要映射的所有字符,那么最简单的方法就是自己定义映射:

If you know all of the characters that you want to map already, the easiest way will simply be to define a mapping yourself:

var eqls = function(first, second) {
    var mappings = { '³': '3', '3': '3' };

    if (mappings[first]) {
        return mappings[first] == mappings[second];
    }

    return false;
}

if (eqls('³', '3')) { ... }

这篇关于如何比较出现相似字符但不同字符代码的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆