如何比较字符相似但字符代码不同的字符串

How to compare strings in which appears similar characters but different char codes?

本文关键字:字符 代码 字符串 相似 比较 何比较      更新时间:2023-09-26

我有一个问题,比较字符串与不同的字符代码,但类似的字符,如以下:

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

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

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

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

等所有数字

谢谢

查看ASCII折叠,它主要用于将重音字符转换为非重音字符。这里有一个JS库。

对于您提供的示例,它将工作-对于其他示例,它可能不工作。这取决于等效性是如何定义的(除了你自己,没人知道你所说的"相似"是什么意思——不同的字符就是不同的字符)。

如果你已经知道你想要映射的所有字符,最简单的方法就是自己定义一个映射:

var eqls = function(first, second) {
    var mappings = { '³': '3', '3': '3' };
    if (mappings[first]) {
        return mappings[first] == mappings[second];
    }
    return false;
}
if (eqls('³', '3')) { ... }

没有"通用解决方案"

如果你只处理数字,你可以建立你的"等价表",为每个支持的字符定义一个"规范"字符。

例如

var eqTable = []; // the table is just an array
eqTable[179] = 51; // ³ --> 3
/* ... */

然后构建一个简单的算法将字符串转换为规范形式

var original,         // the source string - let's assume original=="³3"
var canonical = "";   // the canonical resulting string
var i,
    n,
    c;
n = original.length;
for( i = 0; i < n; i++ )
{
    c = eqTable[ original.charCodeAt( i ) ];
    if( typeof( c ) != 'undefined' )
    {
        canonical += String.fromCharCode( c );
    }
    else
    {
        canonical += original[ i ]; // you *may* leave the original character if no match is found
    }
}
// RESULT: canonical == "33"