0

How do you detect the difference between two similar words?

For example:

  • word compared to word, gives , as a variable
  • this compared to .this gives . as a variable
  • info compared to :info, gives : and , as a variable

In this case we always know which word is the longer one. And the actual word is always the same for the comparison. It's just that the longer one maybe has some extra characters.

I need to do this using javascript only.

Amy Neville
  • 10,067
  • 13
  • 58
  • 94

2 Answers2

3

You could try checking for difference between the array of characters.

var shortStr = 'info';
var longStr = ':info,';

console.log(Array.from(longStr).filter(function(c) {
    return Array.from(shortStr).indexOf(c) === -1;
}));
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

Also, there's a better way, check if the string is a sub-string, and then remove the sub-string from the main string:

function checkDiff(a, b) {
  var big = '', small = '';
  if (a.length > b.length) {
    big = a;
    small = b;
  } else {
    small = a;
    big = b;
  }
  if (big.indexOf(small) != -1) {
    return big.replace(small, "");
  } else {
    return false;
  }
}

alert(checkDiff("word", "word,"));
alert(checkDiff("this", ".this"));
alert(checkDiff("info", ":info,"));

I have added demo for all your cases. It returns the values as a single string, based on the place it has occurred. You can send the output as an array as well, using the .split() method.

function checkDiff(a, b) {
  var big = '', small = '';
  if (a.length > b.length) {
    big = a;
    small = b;
  } else {
    small = a;
    big = b;
  }
  if (big.indexOf(small) != -1) {
    console.log(big.replace(small, "").split(""));
    return big.replace(small, "").split("");
  } else {
    return false;
  }
}

alert(checkDiff("word", "word,"));
alert(checkDiff("this", ".this"));
alert(checkDiff("info", ":info,"));
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252