Last active
June 18, 2020 23:38
-
-
Save JamoCA/94d97a3e4250e0810b8b75423a1dbbc3 to your computer and use it in GitHub Desktop.
Highlight the difference of two texts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!--- 20200618 | |
Bug fix for https://stackoverflow.com/a/38037642/693068 | |
---> | |
<style> | |
.highlighted {background-color:#39ff14;} | |
</style> | |
<script> | |
highlightChanges = function(str, compareStr){ | |
var strlength = str.length > compareStr.length ? compareStr.length : str.length; | |
var allStr = document.createElement("span"); | |
var hl = null; | |
var nohl = null; | |
for(i = 0; i < strlength ; i++){ | |
if(str.charAt(i) != compareStr.charAt(i)){ | |
if(nohl != null){ | |
allStr.appendChild(nohl); | |
nohl = null; | |
} | |
if(hl != null) hl.innerHTML += str.charAt(i); | |
else{ | |
hl = document.createElement("span"); | |
hl.classList.add("highlighted"); | |
hl.innerHTML = str.charAt(i); | |
} | |
} else { | |
if(hl != null){ | |
allStr.appendChild(hl); | |
hl = null; | |
} | |
if(nohl != null) nohl.innerHTML += str.charAt(i); | |
else{ | |
nohl = document.createElement("span"); | |
nohl.innerHTML = str.charAt(i); | |
} | |
} | |
if(hl != null){ | |
allStr.appendChild(hl); | |
} else if (nohl != null){ | |
allStr.appendChild(nohl); | |
} | |
} | |
return allStr; | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment