Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

How to highlight hex code in text while typing

New member
Joined
Feb 8, 2023
Messages
23
I want to highlight the hex code in the text while typing it.

I have a code that looks for a hex code among the already written text and highlights it.

Code:
$(".hwt-highlights").each(function(){
var hex = /#([a-zA-Z0-9]+)/g;
var spanhex = '<mark style="background-color: #$1">#$1</mark>';
this.innerHTML = this.innerHTML.replace(hex, spanhex);
});

But I added this code to the onkeyup event and everything started to work incorrectly.
enter image description here
Each time the button is pressed, the highlight is superimposed on each other. Does anyone know a way to highlight the hex code in the text while it is being printed?
 
New member
Joined
Feb 8, 2023
Messages
5
The pseudo code piece of the problem goes like this:

  1. Take the input of the field where you want the highlight code
  2. Use some regular expression to know whether the text contains your keywords to be highlighed
  3. Use spans with classes to highlight those specific matched words.
Here is some basic code to start on the lines of the implementation, not sure whether this is specifically in sync with your requirement or not:

Code:
// take this input from where ever you want to take
const input = document.querySelector("input");
input.addEventListener("input", function() {
   const text = this.value;
   const hexRegex = /#[0-9a-fA-F]{6}/g;
   const hexCodes = text.match(hexRegex) || [];

   hexCodes.forEach(hexCode => {
       text = text.replace(hexCode, `<span style="background-color: ${hexCode}">${hexCode}</span>`);
   });

   this.innerHTML = text;
});
 
Top