Create a hexadecimal colour based on a string with JavaScript

后端 未结 13 929
旧时难觅i
旧时难觅i 2020-11-30 17:15

I want to create a function that will accept any old string (will usually be a single word) and from that somehow generate a hexadecimal value between #000000

13条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 18:15

    This function does the trick. It's an adaptation of this, fairly longer implementation this repo ..

    const color = (str) => {
        let rgb = [];
        // Changing non-hexadecimal characters to 0
        str = [...str].map(c => (/[0-9A-Fa-f]/g.test(c)) ? c : 0).join('');
        // Padding string with zeroes until it adds up to 3
        while (str.length % 3) str += '0';
    
        // Dividing string into 3 equally large arrays
        for (i = 0; i < str.length; i += str.length / 3)
            rgb.push(str.slice(i, i + str.length / 3));
    
        // Formatting a hex color from the first two letters of each portion
        return `#${rgb.map(string => string.slice(0, 2)).join('')}`;
    }
    

提交回复
热议问题