Home > Web Front-end > JS Tutorial > body text

How to compare the same data in two strings

php中世界最好的语言
Release: 2018-04-18 11:00:24
Original
3211 people have browsed it

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";
Copy after login

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("数字不同");
}
Copy after login

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("数字不同");
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!