13

Stack Overflow's diff view is very good. I want to do this using javascript, but I don't know how to start, who can give some suggestion?

such as: StackOverflow's diff view

Danubian Sailor
  • 1
  • 38
  • 145
  • 223
artwl
  • 3,502
  • 6
  • 38
  • 53

2 Answers2

10

you can try google-diff-match-patch project ,this project offer robust algorithms to perform the operations required for synchronizing plain text.

Demo:http://jsfiddle.net/N6bAn/

Code:

<div class="test">
    <div id="oldStr" class="text">the stackoverflow question and answer version control is very well,i want to do this use javascript,but i don't know how to start,who can give some suggestion?thanks</div>
    <div id="newStr" class="text">Stack Overflow's diff view is very good. I want to do this using  javascript,but i don't know how to start,who can give some suggestion?thanks</div>
</div>
<input type="button" value="GO" onclick="launch()" />
<div class="test">
    <div class="text" id="outputOldStr"></div>
    <div class="text" id="outputNewStr"></div>
</div>
<script type="text/javascript">
    var dmp = new diff_match_patch();

    function launch() {
        var text1 = document.getElementById('oldStr').innerHTML;
        var text2 = document.getElementById('newStr').innerHTML;
        dmp.Diff_EditCost = 8;

        var d = dmp.diff_main(text1, text2);
        dmp.diff_cleanupEfficiency(d);
        var oldStr = "", newStr = "";
        for (var i = 0, j = d.length; i < j; i++) {
            var arr=d[i];
            if (arr[0] == 0) {
                oldStr += arr[1];
                newStr += arr[1];
            } else if (arr[0] == -1) {
                oldStr += "<span class='text-del'>" + arr[1] + "</span>";
            } else {
                newStr += "<span class='text-add'>" + arr[1] + "</span>";
            }
        }
        document.getElementById('outputOldStr').innerHTML = oldStr;
        document.getElementById('outputNewStr').innerHTML = newStr;
    }
</script>
programmer
  • 116
  • 5
  • 2
    I went through this and ended up creating a wrapper library to help with the "presentation work" needed to use `diff_match_patch`: https://github.com/arnab/jQuery.PrettyTextDiff – or9ob Jan 24 '13 at 11:29
  • Angular wrapper for `google-diff-match-patch`: https://github.com/amweiss/angular-diff-match-patch – fiat Apr 28 '16 at 05:01
  • 4
    Updated JS fiddle, It was not working. http://jsfiddle.net/ac13t0xp/2/ – Deepak Gangore Apr 05 '19 at 06:49
4

There are JavaScript libraries that does diff visualization. These are a few examples I found:

I haven't tried any of them, so unfortunately I can't tell you which is most suited for you needs, but it might be worth checking them out.

Update

jsdifflib looks promising, there is a demo available that you could try.

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103