0

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.)

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
  • 2
    ouch! i guess this is not simple to do it from scratch, did you search for clues on implementations or libraries already made? If Levenshtein algorithm counts the minimum changes to go from one to another, can't it list them too? I'm not a specialist, but i feel there's a link with pattern recognition.. – Kaddath Jul 27 '17 at 08:13
  • https://stackoverflow.com/questions/38037163/how-to-highlight-the-difference-of-two-texts-with-css – Kalvisan Nov 24 '17 at 09:53

0 Answers0