Show Diff with Copy of Destination Text
For a web application I needed to show the difference between two texts.
First I tried calculating this in the backend (Python) but using fast-diff in Javascript was easier.
The important part here was the possibility to mark and copy only the destination part of the difference.
The result of a
diff
call is a list of tuples: "equal (0), insert (+1), delete (-1)" and the character at this position.Now every change is added with either
<span>
or with <del>
.All
<del>
segments are not part of the marking when copied.The color classes are for Bulma (yellow background for inserts, red strikethrough for deletes).
Example code:
var difference = diff("abc", "ace"); // result: [[0, 'a'], [-1, 'b'], [0, 'c'], [1, 'e']] var r = "" difference.forEach(e => { if (e[0] == 0) { r = r + e[1]; } else if (e[0] == 1) { r = r + '<span class="has-background-warning">' + e[1] + "</span>"; } else if (e[0] == -1) { r = r + '<del class="has-text-danger">' + e[1] + "</del>"; } }); console.log(r); // "a<del class="has-text-danger">b</del>c<span class="has-background-warning">e</span>"
Example rendered:
The first line is the rendered string and the second line is the same rendered string marked.
Important here, the <del>
part is not part of the marking.