简体   繁体   English

JS 用新的随机 HEX 颜色替换每种 HEX 颜色

[英]JS Replace each HEX color with a new random HEX color

Recently I've asked on how to replace a thousand of #FFF with a random HEX color.最近我问过如何用随机的十六进制颜色替换一千个#FFF。 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.我正在寻找一种方法来检测文件中的任何 HEX 颜色,并将其替换为新的随机 HEX 颜色。 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另外, ("000000" + Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6)是我获得 HEX 颜色的唯一方法,如Math.floor(Math.random()*16777215).toString(16)方法在我的网页上引发错误

Replace data.replace(/^#[0-9A-F]{6}$/i.test('#AABBCC'), () => '#' + ("000000" + Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6));替换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)我在您的正则表达式中添加了global标志,并找到了一种更短的方法来从这里生成随机颜色,除了删除不必要的.test并删除^ / $ (匹配字符串开头)

Here is my function to generate a random HEX color:这是我的 function 生成随机十六进制颜色:

function randomHEX(){
    const hex = (Math.random()*0xFFFFFF<<0).toString(16);
    return `#${hex}`;
}

Generate random hex color :生成随机十六进制颜色

function rndHex(){return'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM