两个词之间的JavaScript差异

艾米·内维尔(Amy Neville)

您如何检测两个相似词之间的差异?

例如:

  • wordword,,定变量相比
  • this.this.定变量相比
  • info:info,给出:,作为变量相比

在这种情况下,我们总是知道哪个单词更长。与实际的单词进行比较时始终是相同的。只是更长的一个可能会有一些额外的字符。

我只需要使用javascript就能做到这一点。

Praveen Kumar Purushothaman

另外,还有一种更好的方法,检查字符串是否为子字符串,然后从主字符串中删除子字符串:

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

我已经为您的所有案例添加了演示。它根据发生的位置将值作为单个字符串返回。您也可以使用.split()方法将输出作为数组发送

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章