Lau Lau - 1 month ago 17
Javascript Question

text highlighting (from scratch) output issue

I'm trying to build a simple color highlighter using a textarea calling a function on keyup, and a div to output the result (highlighted/colored text).

The words to be highlighted and their associated color are stored in this object :

var obj = {
"to": "green",
"code": "red",
"applet": "blue"
}


The input string is then split into word units to check if they match the
obj
keys.

var splitRequest = input.value.toLowerCase().split(' ');


If they do, then they should be highlighted. I wrote a simple code that does the trick (see fiddle at the end), except for this line :

output.innerHTML += '<span style="color:' + obj[splitRequest[i]] + '">' + splitRequest[i] + " </span>";


It prints the whole text on each keypress instead of replacing the current content with the new one because of the
+=
sign. Problem is that I can't simply use the
=
sign because it will only print the first element of the
splitRequest
array instead of the whole array. I tried to use the
join()
method but it obviously didn't work as I expected (test).

Maybe the code itself isn't so good and I should use another approach to get it working. This would be a great way to learn javascript better, but I actually have no idea how to do this.

How can I output the text user types in while highlighting the matching words without having this problem ?

Here is the working demo where I'm stuck : https://jsfiddle.net/Lau1989/9oL7umtt/1/

Thanks for your help

PS : I know there are third-parties availables for syntax highlighting, but for the sake of educating myself I'm trying to code it from scratch using pure javascript (no jQuery).

Answer

add

output.innerHTML = "";

after

var output = document.getElementById('output');

on LINE 9

https://jsfiddle.net/Lauy79kv/