【发布时间】:2022-12-07 06:12:55
【问题描述】:
我有一个(有点)工作解决方案,它找到已添加到字符串中的值,但是当值被删除时它会下降
function highlightDifferences(newValue, oldValue) {
if (oldValue === '' || newValue === oldValue) // Just return if the old value is empty or if the two values match
return newValue;
var highlightedCharacter = ""; // returnText will be modifed below
var oldValueArray = oldValue.split('');
var newValueArray = newValue.split('');
var returnArray = [];
for (var x = 0; x < newValue.split('').length; x++) {
if (oldValueArray[0] !== undefined && oldValueArray[0] === newValueArray[0]) {
returnArray.push(newValueArray[0]); // add the un-highlighted character to the return array
oldValueArray.shift(); // if the two characters are the same, drop them and move to the next character for comparison
newValueArray.shift();
}
else {
highlightedCharacter = '<span class="highlight">' + newValueArray[0] + '</span>';
returnArray.push(highlightedCharacter); // add the highlighted character to the return array
newValueArray.shift(); // remove the unmatched character from the array. oldValueArray is unchanged to compare to the next character in the newValue array
}
}
return returnArray.join('');
}
var oldValue = document.getElementById("oldValue").innerText;
var newValue = document.getElementById("newValue").innerText;
var text = highlightDifferences(newValue,oldValue);
document.getElementById("compared").innerHTML = text;
var oldValue2 = document.getElementById("oldValue2").innerText;
var newValue2 = document.getElementById("newValue2").innerText;
var text = highlightDifferences(newValue2,oldValue2);
document.getElementById("compared2").innerHTML = text;
.highlight {
background-color: #fdff674d;
color: red;
}
<div><strong>Old:</strong> <span id="oldValue">https://somedomain.info/ac834b89e</span></div>
<div><strong>New:</strong> <span id="newValue">https://55some5domain.i555nfo/ac834b89e</span></div>
<div><strong>Show Added characters: </strong><span id="compared">to be replaced</spanid></div>
<hr />
<div><strong>Old:</strong> <span id="oldValue2">https://somedomain.info/ac834b89e</span></div>
<div><strong>New:</strong> <span id="newValue2">https://55some.i555nfo/ac834b89e</span></div>
<div><strong>Result with removed characters: </strong><span id="compared2">to be replaced</spanid></div>
您会看到删除字符后结果的突出显示不正确。 我如何“展望”未来的比赛以检测删除的字符?
【问题讨论】:
-
仅供参考,有一个名为“diff”的 unix 程序已经存在了很长时间。我不知道这是否可以按照您希望的方式集成到您的项目中,但是对于比较文档的两个版本,diff 很棒
-
@ControlAltDel 谢谢。我找到了一个 JS 版本:npmjs.com/package/diff 我真的不想求助于使用包,但避免重新发明轮子可能是值得的
-
很高兴听到你跟进我的建议!我自己正在使用 PHP“diff”端口
-
重新:......值得避免重新发明......对于专业工作的IMO,在自己做之前应该总是寻找使用包;除非你在一家销售你正在开发的软件的公司工作,否则软件就像一辆送货卡车——对企业很重要,但对企业来说并不重要。就像送货卡车一样,它有建造或购置成本、预期的“使用寿命”以及沿途的维护成本。因此,如果您可以将 3rd party 与您的代码堆栈一起使用,“免费维护”可能是一个胜利。
标签: javascript arrays string