Last active
December 28, 2022 08:45
-
-
Save stephanbogner/48d19c30849a4f5fbdc5374111c3ca31 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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