How can I visualize all changes in one string compared to another?

柔情痞子 提交于 2020-01-07 04:11:06

问题


Currently, I use https://jsfiddle.net/MartinThoma/h9kL6zox/1/ (see this answer) to highlight changes from one string (< 255 chars) to another string (<255 chars). I can only add highlighting code to one of them.

There are three types of changes which I would like to highlight:

  • C1: Insertions
  • C2: Deletions
  • C3: Changes

Here is the current code:

highlight($("#new"), $("#old"));

function highlight(newElem, oldElem){ 
    var newText = newElem.text();
    var oldText = oldElem.text();

    var text = "";
    var spanOpen = false;
    newElem.text().split("").forEach(function(value, index){
                if (value != oldText.charAt(index)){   
            text += !spanOpen ? "<span class='high'>" : "";
            text += value;
            spanOpen = true;
        } else {       
            text += spanOpen ? "</span>" : "";
            text += value;
            spanOpen = false;  
        }    
    });
    newElem.html(text);
}

As you can see, it only works with (C3). How do I make it work with the other two types of changes?

(I think this is probably related to the Levenshtein algorithm which calculates the distance. I need a bit more - I need to show where the differences are.)

来源:https://stackoverflow.com/questions/45344295/how-can-i-visualize-all-changes-in-one-string-compared-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!