Skip to content

Instantly share code, notes, and snippets.

@lewdev
Created March 21, 2025 01:07
Show Gist options
  • Save lewdev/24b45604e1c1156414ca785fde648ce2 to your computer and use it in GitHub Desktop.
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment