This time I will show you how to compare the same data in two strings, and what are the precautions when comparing the same data in two strings , the following is a practical case, let’s take a look.
There are two strings:
$a = "5,8,0"; $b = "8,0,5";
How to quickly compare the numbers contained in these two strings are the same, the delimiters are the same, but the order of the numbers is different, the length of the two strings is the same
js code:
Method 1:
var s1 = "5,0,8"; var s2 = "8,0,5"; if(s1.split(",").sort().join(",") == s2.split(",").sort().join(",")) { alert("数字相同"); }else{ alert("数字不同"); }
Method 2:
var s1 = "5,0,8"; var s2 = "8,0,5"; var a1 = s1.split(","); var a2 = s2.split(","); var isSame = false; if (a1.length == a2.length) { isSame = true; var length = a2.length; for (var i = 0; i < length; i++) { if (a1.indexOf(a2[i]) < 0) { isSame = false; break; } } } if (isSame) { alert("数字相同"); } else { alert("数字不同"); }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
The above is the detailed content of How to compare the same data in two strings. For more information, please follow other related articles on the PHP Chinese website!