Created
December 30, 2017 17:44
-
-
Save olehmelnyk/40f46c7f05bf2fdd6d897338a48755c6 to your computer and use it in GitHub Desktop.
get HEX/RGB/CMYK by Pantone code (parse official Pantone website search result)
This file contains 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
// get HEX/RGB/CMYK by Pantone code (parse official Pantone website search result) | |
async function pantone(pantoneCode){ | |
pantoneCode = pantoneCode // validate input: | |
.trim() | |
.replace(/^PANTONE /i, '') // we don't need 'PANTONE ' here | |
.replace(/ /g, '-'); // no spaces | |
return fetch(`https://www.pantone.com/color-finder/${pantoneCode}`) | |
.then(response => response.text()) | |
.then(doc => new DOMParser().parseFromString(doc, 'text/html')) | |
.then(html => { | |
let data = {}; | |
let dataset; | |
let swatchContainer = html.querySelector('.swatchContainer'); | |
if(swatchContainer) dataset = swatchContainer.dataset; | |
else return 'Error 404: Pantone not found'; | |
if(dataset.colorCode) data.code = dataset.colorCode; | |
if(dataset.colorName) data.name = dataset.colorName; | |
let hex = html.querySelector('#ctl00_cphContent_ctl00_divHEXValues'); | |
if(hex) data.hex = hex.innerText.trim(); | |
let rgb = html.querySelector('#ctl00_cphContent_ctl00_divRGBValues'); | |
if(rgb) data.rgb = rgb.textContent.replace(/\s{2,}/g, ' ').trim().split(' ').map(Number); | |
let cmyk = html.querySelector('#ctl00_cphContent_ctl00_divCMYKValues'); | |
if(cmyk) data.cmyk = cmyk.textContent.replace(/\s{2,}/g, ' ').trim().split(' ').map(Number); | |
return data; | |
}); | |
} | |
// example tests: | |
console.log( | |
(await pantone('PQ-19-0303TCX')), // this example has name but doesn't have a cmyk | |
(await pantone('Pantone Black 2 C')) // this example has cmyk but doesn't have a name | |
); | |
console.log( | |
'Error example here >>', | |
(await pantone('PANTONE XXL C')) // error: pantone not found | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment