如何比较2个字符串相似的字符串?

时间:2017-06-28 13:54:34

标签: javascript

以下代码是我问题的最小代表。应该怎样做才能使if条件为真,以便打印 IP地址匹配!

我知道两个字符串的编码都有问题。我正在寻找一个答案,将两个字符串转换为一些传递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!");
}

2 个答案:

答案 0 :(得分:0)

您可以用点替换非数字字符。



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!");
}




答案 1 :(得分:0)

根据评论中的讨论,我发布了这个在“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!");
}