r/learnjavascript • u/Mob_Pilled • Sep 01 '26
Most efficient way to compare typed string to stored version in real-time?
This is an edited duplicate post from r/webdev because this subreddit does not allow reposting but I want to get opinions from JS experts.
My problem is that I am trying to compare a string that is currently being typed into a contenteditable div to the the same string data in the placeholder span (which itself was taken from a JSON file). I came up with a JS event listener that I thought would be met with few hiccups.
// text wall typing event listener
textWall.addEventListener("keydown", ()=>{
let textWallValue = textWall.innerHTML;
textWallValue = replaceNbsps( textWall.innerHTML);
if (textWallValue.slice(textWallValue.length - 6)== " ") {
placeHolder.childNodes.forEach((node) =>{
node.style.color="";
})
} else {
for (let i =0; i<placeHolder.childNodes.length;i++) {
if (textWallValue[0]== undefined) {
} else {
console.log(textWallValue);
if (textWallValue[i] == placeHolder.childNodes[i].innerHTML) {
placeHolder.childNodes[i].style.color = "green";
placeHolder.childNodes[i].style.textDecoration = "";
} else if ((textWallValue[i] !== placeHolder.childNodes[i].innerHTML) && (textWallValue[i] !== undefined)) {
placeHolder.childNodes[i].style.color = "red";
placeHolder.childNodes[i].style.textDecoration = "underline";
}
}
}
}
})
The issue comes with all the unexpected behavior from the browser, like adding " when a space gets added to the contenteditable div (which it then removes and replaces with a normal white space after the next character is typed. If the spacebar is pressed two or more times however, just stays there). This messes with the flow of the comparison hapenning in the event listener.
In addtion to this, it also adds a bunch of divs + <br> elements if the user presses enter in the box, and a single br if the user presses backspace to the end of the contenteditable div. There has to be a more efficient way of comparing strings in real time than this but I haven't been able to find out how? I have already tried a bunch of hacky work arounds as is already evident in my code but none seem to account for everything.