问题陈述:两个输入字符串,其格式如HTML中的strong,li,ol,line-through等。在屏幕上,应该有两个框:原始文本和编辑文本。如果编辑文本中缺少任何原始文本文本,则应突出显示该红色字。如果他在“编辑文本”中添加了任何不在“原始文本”中的内容,则应在“编辑文本”中突出显示黄色文本
预期输出:在第一个框中,它应突出显示红色的已删除文本。在第二个框中,它应突出显示黄色的编辑文本
解决方法尝试:: 1>尝试使用DIff Match Patch但由于输入字符串包含html字符串而无法正常工作。我无法剥离标签,因为它将失去其样式。
2>尝试使用HtmlDiff,但这会在单个字符串中同时提供已删除的单词和修改后的单词。很难修改这个库。
任何领导或帮助将不胜感激。谢谢
通过将文本拆分为字符串数组(由char''拆分),可以更轻松地手动比较HTML代码的字符串。
例如,对于问题的第1部分,您可以比较单词(字符串数组)并使用类highlightRed添加跨度以使背景变为红色。
示例:https://codepen.io/vck3000/pen/xYeLKq/?editors=1111
//get the strings
var div1Text = document.querySelector("#div1").innerHTML;
var div2Text = document.querySelector("#div2").innerHTML;
//split the strings
var div1TextSplitted = div1Text.split(" ");
var div2TextSplitted = div2Text.split(" ");
//variables to cycle through the split string
var wordNumber1 = 0;
var wordNumber2 = 0;
//new string to re-assign to the divs
var newDiv1Text = "";
var newDiv2Text = "";
//Part 1: Red highlight
while(true){
//if we find a word that ISNT the same
if(div1TextSplitted[wordNumber1] !== div2TextSplitted[wordNumber2]){
//add in a span
newDiv1Text += "<span class='highlightRed'>" + div1TextSplitted[wordNumber1] + "</span> ";
//increment the variables
wordNumber2++;
wordNumber1++;
}
//otherwise we have the same text
else{
//append the same text with no changes
newDiv1Text += div1TextSplitted[wordNumber1] + " ";
//increment variables
wordNumber1++;
wordNumber2++;
}
//if we reach the end of either string, break
if(div1TextSplitted[wordNumber1 + 1] === undefined || div2TextSplitted[wordNumber2 + 1] === undefined){
break;
}
}
//re-assign the new text to the div
document.querySelector("#div1").innerHTML = newDiv1Text;
第2部分(突出显示黄色)将是一个类似的任务,但稍微更难。看看你是否能搞清楚。