Amy Neville Amy Neville - 7 months ago 26
Javascript Question

Javascript difference between two words

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.

Answer

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,"));

Comments