简体   繁体   English

如何比较两个具有相似字符的字符串?

[英]How to compare 2 strings with similar characters?

The below code is a minimal representation of my problem. 以下代码是我的问题的最小表示。 What should be done to make the if condition true so that it prints IP Addresses match! 应该做些什么才能使if条件为true,以便它打印的IP地址匹配! ?

I know there's a problem with encoding of both strings. 我知道两个字符串的编码都有问题。 I am looking for an answer that converts both strings to some uniform encoding that passes the if condition. 我正在寻找一个将两个字符串都转换为通过if条件的统一编码的答案。

 var ip1="127.0.0.1"; var ip2="127․0․0․1"; //127%u20240%u20240%u20241 if(ip1 === ip2){ console.log("IP Addresses match!"); }else{ console.log("IP Addresses do not match!"); } 

You could replace non digit characters with dot. 您可以将非数字字符替换为点。

 var ip1 = "127.0.0.1", ip2 = "127․0․0․1"; ip1 = ip1.replace(/\\D+/g, '.'); ip2 = ip2.replace(/\\D+/g, '.'); if (ip1 === ip2){ console.log("IP Addresses match!"); } else { console.log("IP Addresses do not match!"); } 

Based on the discussion in comments, am posting this answer which uses normalize function in "NFKD" mode. 根据评论中的讨论,我将发布此答案,该答案在“ NFKD”模式下使用规范化功能。

 var ip1="127.0.0.1"; var ip2="127․0․0․1"; //127%u20240%u20240%u20241 if(ip1.normalize("NFKD") === ip2.normalize("NFKD")){ console.log("IP Addresses match!"); }else{ console.log("IP Addresses do not match!"); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM