您如何检测两个相似词之间的差异?
例如:
word
与word,
给,
定变量相比this
与.this
给.
定变量相比info
与:info,
给出:
和,
作为变量相比在这种情况下,我们总是知道哪个单词更长。与实际的单词进行比较时始终是相同的。只是更长的一个可能会有一些额外的字符。
我只需要使用javascript就能做到这一点。
另外,还有一种更好的方法,检查字符串是否为子字符串,然后从主字符串中删除子字符串:
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] 删除。
我来说两句