JS implementation to compare whether two strings separated by the specified separator are the same

  • 2020-03-30 03:57:26
  • OfStack

Compare the differences between elements in 2 strings (character 1, character 2, separator optional)

Documents: the diff. Js


//Sample usage
/*

var str1 = "tie, mao, 55";
var str2 = "tie, mao, csdn";
var result = diff(str1, str2, ','); //  object 
var rs = "" + result;  // " 55, csdn"
var df1 = result.diff1; // [" 55"]
var df2 = result.diff2; // [" csdn"]

*/

//Compare the differences between elements in 2 strings (character 1, character 2, separator optional)
function diff(str1, str2, separator){
	//
	str1 = str1 || "";
	str2 = str2 || "";
	separator = separator || ",";
	//There is an ele element in arr
	function hasElement(arr, ele){
		//Memory cycle
		var hasItem1 = false;
		for(var i2=0; i2 < arr.length; i2++){
			//
			var item2 = arr[i2] || "";
			if(!item2){
				continue;
			}
			//
			if(ele == item2){
				hasItem1 = true;
				break;
			}
		}
		return hasItem1;
	};
	function inAnotB(a, b){ //In A, not in B
		var res = [];
		for(var i1=0; i1 < a.length; i1++){
			var item1 = a[i1] || "";
			if(!item1){
				continue;
			}
			var hasItem1 = hasElement(b, item1);
			if(!hasItem1){
				res.push(item1);
			}
		}
		return res;
	};
	//
	var list1 = str1.split(",");
	var list2 = str2.split(",");
	//
	var diff1 = inAnotB(list1, list2);
	var diff2 = inAnotB(list2, list1);
	
	//Returns the result
	var result = {
		diff1 : diff1
		,
		diff2 : diff2
		,
		separator : separator
		,
		toString : function(){
			//
			var res = this["diff1"].slice(0);
			res = res.concat(this["diff2"]);
			//
			return res.join(this["separator"]);
		}
	};
	//
	return result;
};

Please use it as needed to compare which tables I exported in the two Oracle databases did not import successfully.


Related articles: