Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Changing hex color from string's color

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!