Home > Net >  Changing hex color from string's color
Changing hex color from string's color

Time:05-10

So I've seen a bunch posted like this but none solved anything for me.


const HexPattern = /(#[0-9a-f]{6})(\s*[\w,] \s*)/gi

function parseColors(str) {
  return str.replace(HexPattern, (s, g0, g1) => `<span style="color:${g0}">${g1}</span>`)
}

If I were to use this code it would replace the text after the hex color in the string with the color but I would want to change the actual hex color string into that color so like if my string was:

let string = "hello there #191919 <-- see that thats black"

it would change the #191919 into the hex color represented there and not the text after like my current code does which I found on stackoverflow.

CodePudding user response:

The issue in your question is all in the regex. If you only want to replace the hex colour value in the string with that colour then the second matching group, (\s*[\w,] \s*), can be removed.

That leaves you with this: /(#[0-9a-f]{6})/gi. However it's worth noting that a valid hex colour code can have 3, 6 or 8 characters, so you may also need to cater for that. The example below shows you how to do this:

const hexPattern = /(#[0-9a-f]{8}|#[0-9a-f]{6}|#[0-9a-f]{3})/gi
let parseColors = str => str.replace(hexPattern, (s, match) => `<span style="color:${match}">${match}</span>`);

$('div').html((i, t) => parseColors(t));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>Some 3 character hex values: #C00 and #937</div>
<div>Some 6 character hex values: #545234 and #C8929A</div>
<div>Some 8 character hex values: #A63098FF and #00000066</div>

  • Related