Reputation: 177
Recently I've asked on how to replace a thousand of #FFF with a random HEX color. The solution was to run this code:
var fs = require('fs')
fs.readFile('stars.css', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace(/#FFF/g, () => '#' + ("000000" + Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6));
fs.writeFile('stars.css', result, 'utf8', function (err) {
if (err) return console.log(err);
});
});
I'm looking for a way to detect any HEX color within the file, and replace it with a new random HEX color. Here's what I tried:
var result = data.replace(/^#[0-9A-F]{6}$/i.test('#AABBCC'), () => '#' + ("000000" + Math.random().toString(16).slice>
Also, ("000000" + Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6)
is the only way for me to get HEX color, as Math.floor(Math.random()*16777215).toString(16)
method throws an error on my webpage
Upvotes: 1
Views: 266
Reputation: 21639
function rndHex(){return'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6)}
Upvotes: 0
Reputation: 1124
Here is my function to generate a random HEX color :
function randomHEX(){
const hex = (Math.random()*0xFFFFFF<<0).toString(16);
return `#${hex}`;
}
Upvotes: 1
Reputation: 1412
Replace data.replace(/^#[0-9A-F]{6}$/i.test('#AABBCC'), () => '#' + ("000000" + Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6));
with:
data.replace(/#[0-9A-F]{3,6}/ig, () => `#${Math.floor(Math.random()*16777215).toString(16)}`);
I added global
flag to your regex and found a shorter way to generate a random color from here, besides removing unnecessary .test
and deleting ^
/$
(matches at the start of the string)
Upvotes: 1