Skip to content

Instantly share code, notes, and snippets.

@JamoCA
Last active June 18, 2020 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamoCA/94d97a3e4250e0810b8b75423a1dbbc3 to your computer and use it in GitHub Desktop.
Save JamoCA/94d97a3e4250e0810b8b75423a1dbbc3 to your computer and use it in GitHub Desktop.
Highlight the difference of two texts
<!--- 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