Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active June 26, 2026 18:55
Show Gist options
  • Select an option

  • Save lewdev/24b45604e1c1156414ca785fde648ce2 to your computer and use it in GitHub Desktop.

Select an option

Save lewdev/24b45604e1c1156414ca785fde648ce2 to your computer and use it in GitHub Desktop.
πŸ’¬ Text Diff Highlighter. `highlightDiff` compares 2 strings and displays text that was added & removed

highlightDiff compares two strings and

  • 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>
<style>
:root{color-scheme:dark}
td{width:33%;min-width:200px}
textarea{width:100%;height:calc(100vh - 5rem)}
</style>
String Diff
<table border=1 style=border-collapse:collapse;width:100%><tbody><tr id=r></tr></tbody></table>
<script>
sanitize = s => s.replace(/</g,"&lt;").replace(/>/g,"&gt;");
HD=(s1, s2) => {
let result = "", i = j = 0;
s1 = sanitize(s1);
s2 = sanitize(s2);
const s1Len = s1.length;
const s2Len = s2.length;
while (i < s1Len || j < s2Len) {
if (s1[i] !== s2[j]) {
let added = removed = '';
while (s1[i] !== s2[j] && j < s2Len) {
if (s1[j]) removed += s1[j];
added += s2[j++];
}
result += `<s>${removed}</s><span style="background-color:green">${added}</span>`;
}
if (i < s1Len) i++;
if (j < s2Len) result += s2[j++];
}
return result;
};
G=_=>o.innerHTML = HD(s0.value, s1.value);
onload=_=>r.innerHTML=`${Array(2).fill().map((_,i)=>`<td><textarea id=s${i} oninput=G()></textarea></td>`).join``}<td id=o></td>`
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment