- adds a strikethrough attribute to text that was removed and
- adds a green highlight over the text that was added.
It's very simple solution that works for most situations.
<pre id=o></pre>
<script>
function highlightDiff(str1, str2) {
let result = "", i = j = 0;
const s1Len = str1.length;
const s2Len = str2.length;
while (i < s1Len || j < s2Len) {
if (str1[i] !== str2[j]) {
let added = removed = '';
while (str1[i] !== str2[j] && j < s2Len) {
if (str1[j]) removed += str1[j];
added += str2[j++];
}
result += `<s>${removed}</s><span style="background-color: #0F0;">${added}</span>`;
}
if (i < s1Len) i++;
if (j < s2Len) result += str2[j++];
}
return result;
}
const string1 = `This is the first string asfsad`;
const string2 = `This is the first string
sadf
33`;
o.innerHTML = highlightDiff(string1, string2);
</script>