You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改JavaScript代码实现将字符串中的十六进制颜色值文本设置为对应颜色

Fix: Colorize the Hex Color Value Itself

Got it, let's adjust your code so it targets the hex color string itself instead of the text after it. The issue with your current code is that your regex captures the hex value and the following text, then wraps only the following text in the colored span. We need to flip that to wrap the hex value itself.

Here's the revised code:

const HexPattern = /(#[0-9a-f]{6})/gi;
function parseColors(str) {
  return str.replace(HexPattern, (match) => `<span style="color:${match}">${match}</span>`);
}

How this works:

  • The regex /(#[0-9a-f]{6})/gi now only captures the 6-digit hex color value itself (no extra text after it).
  • In the replace callback, we take the matched hex value (match), wrap it in a <span> where the color style is set to that same hex value, and return that span. The rest of the original string stays exactly as it was.

Example test:

If you run:

let string = "hello there #191919 <-- see that thats black";
console.log(parseColors(string));

You'll get this output:

hello there <span style="color:#191919">#191919</span> <-- see that thats black

Now the #191919 text will display in the black color it represents, just like you wanted!

内容的提问来源于stack exchange,提问作者moie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:52:49