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

家住魔仙堡 提交于 2019-12-12 04:22:11

问题


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

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....

Thanks


回答1:


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')) { ... }



回答2:


There is no "universal solution"

If you've only to deal with digits you may build up your "equivalence table" where for each supported character you define a "canonical" character.

For example

var eqTable = []; // the table is just an array

eqTable[179] = 51; // ³ --> 3
/* ... */

Then build a simple algorythm to turn a string into its canonical form

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"


来源:https://stackoverflow.com/questions/39948627/how-to-compare-strings-in-which-appears-similar-characters-but-different-char-co

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