-2

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>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Omar Abdelrazik
  • 683
  • 2
  • 9
  • 30
  • If you have to match only one word, instead of `.*?` you could use `\S+` – lemon Jul 02 '22 at 18:58
  • 2
    Markup in ` – Pointy Jul 02 '22 at 19:01
  • Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Jul 02 '22 at 19:03
  • Next time take more care with the description. I hammer closed with a dupe because you mentioned a textarea in the title – mplungjan Jul 02 '22 at 19:04

2 Answers2

1

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>
lemon
  • 14,875
  • 6
  • 18
  • 38
0

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>
Mina
  • 14,386
  • 3
  • 13
  • 26
  • The subject was not right, its a `span` not a `textarea`. I was able to make it change color before with this `text = text.replace(/(%match.*?)/gi, "$1") ` but it didnt replace the `%`. – Omar Abdelrazik Jul 02 '22 at 19:05
  • your suggestion doesnt do anything. It doesnt even remove the `%` I am afraid. – Omar Abdelrazik Jul 02 '22 at 19:06
  • it removed the `%` and add the word in span with green color, this is the question description, you can run the code snippet and see. – Mina Jul 02 '22 at 19:08