Home > Back-end >  How do I find the difference between two strings and return the difference value?
How do I find the difference between two strings and return the difference value?

Time:11-26

I can compare the length but, I can't return mismatch value.

var str1 ="zoho";
var str2 ="zogo";

//find the mismatched one
let output = hg;
let names = "zoho";
let nam2= "zogo"
let rest = names.match(nam2)
 
console.log(rest);

CodePudding user response:

If you expect the two strings have the same length, and the two words have the same characters sequence.

const findDifference = (first, second) => {
  let diff = ''
  for (let i = 0; i < first.length; i  ) {
    if (first[i] !== second[i]) {
      diff  = first[i]   second[i];
    }
  }
  return diff
}

console.log(findDifference('zoho', 'zogo'));

Otherwise, If you want to check the two words similarity, I suggest you to check Levenshtein distance

CodePudding user response:

Covering length of strings are same/different cases;

const findDifference = (str1, str2) => {
  let result = "";
  if (str1.length >= str2.length) {
     str1.split("").forEach((char, index) => {
      if (char!=str2[index]) {
        result = result   char   (str2[index] || '');
      }
     });
  } else {
    str2.split("").forEach((char, index) => {
      if (char!=str1[index]) {
        result = result   (str1[index] || "")   char;
      }
     });
  }
  return result;
}
 
console.log(findDifference("zoho", "zogo"));
console.log(findDifference("zohox", "zogo"));
console.log(findDifference("zoho", "zogox"));
console.log(findDifference("zoho", ""));
console.log(findDifference("", "zogo"));

results are hg hgx hgx zoho zogo respectively.

CodePudding user response:

Try this (This solution will also work if you have strings with different length) :

var str1 ="zoho";
var str2 ="zogo";

let differenceValue = '';

Array(Math.max(str1.length, str2.length)).fill().forEach((v, index) => {
  if (str1[index] !== str2[index]) {
    differenceValue  = (str1[index] ?? '')   (str2[index] ?? '');
  }
})

console.log(differenceValue);

  • Related