Home > front end >  Removing characters and changing color of text in label doesn't work
Removing characters and changing color of text in label doesn't work

Time:07-03

I want to replace every word starting with % with the same word without the % and changing its color to green.

However, all I can do is remove the % without changing colors.

Is there something I am missing here?

var text = "Lite %match Color"
text = text.replace(/%(.*?)/g, "<span style='color: green'>$1</span>")
document.getElementById("output").innerHTML = text
<label id="output"></label>

CodePudding user response:

The problem with your regex is that, given that you have no lookahead after the .*?, it will match the least amount of characters, which is none at all. In order to fix this problem, you can substitute that part with \S , that attempts to match any non-space characters (at least one).

var text = "Lite %match Color"
text = text.replace(/%(\S )/g, "<span style='color: green'>$1</span>")
document.getElementById("output").innerHTML = text
<label id="output"></label>

CodePudding user response:

var text = "Lite %match Color"
  text = text.replace(/\s %(.*?)\s /g, "<span style='color: green'> $1 </span>")
  document.getElementById("output").innerHTML = text
<div id="output"> </div>

  • Related