Skip to content

Instantly share code, notes, and snippets.

@extratone
Forked from stephanbogner/example.html
Created September 21, 2022 18:16
Show Gist options
  • Save extratone/e5c1eb1315680aca0ba6983c0b7198b7 to your computer and use it in GitHub Desktop.
Save extratone/e5c1eb1315680aca0ba6983c0b7198b7 to your computer and use it in GitHub Desktop.
Extract hex color codes from a string (e.g. text, SVG, HTML, XML) using a regex in JS
<script type="text/javascript">
let testString = ''
testString += '<div style="color: #00A9F8"></div><div style="color: #12345"></div>';
testString += '<div style="color: 00A9F8"></div><div style="color: #123456"></div>';
testString += '<div style="color: #fff"></div><div style="color: #000"></div>';
let regularExpression = /#(?:[0-9a-fA-F]{3}){1,2}/g // btw: this is the same as writing RegExp(/#(?:[0-9a-fA-F]{3}){1,2}/, 'g')
let extractedHexCodes = testString.match(regularExpression);
console.log(extractedHexCodes)
// -> Output ["#00A9F8", "#123", "#123456", "#fff", "#000"]
</script>
<!--
Note on the HEX codes:
- Must start with a # (if you don't want this you can remove the `#` from the regularExpression, but this might match some random strings also)
- Must either 3 or 6 digits long (because otherwise they are not valid hex codes)
Sources:
- The regex itself: https://stackoverflow.com/questions/51416039/how-to-extract-hex-colors-from-html/51418376#51418376
- Match all: https://stackoverflow.com/questions/6323417/regex-to-extract-all-matches-from-string-using-regexp-exec
- Regex tutorial: https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285
- Regex JS syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll
- (Handy tool) Debug regex: https://regex101.com/
-->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment