mercredi 15 juillet 2020

Replace all hashes in a string with a random value

What would be the best way of iterating through all the # in the constant styles and replacing them with a randomly generated hex colour. For example:

generateRandomStyle(colours: string[]): string {
  const styles = [
    'filter:drop-shadow(1px -1.5px 0px #) drop-shadow(-1px 1.5px 0px #);',
    'filter:drop-shadow(1.5px -1px 0px #);',
  ];
  const rgbaColor = UtilService.hexToRgbA(`#${colours[Math.floor(Math.random() * colours.length)]}`);
  let style = styles[Math.floor(Math.random() * styles.length)];
  style = style.replace('#', rgbaColor);
  return style;
}

I'd expect the output to be filter:drop-shadow(1px -1.5px 0px rgba(102,102,153,1)) drop-shadow(-1px 1.5px 0px rgba(106,101,159,1));or something. But I get the output filter:drop-shadow(1px -1.5px 0px rgba(102,102,153,1)) drop-shadow(-1px 1.5px 0px #).




Aucun commentaire:

Enregistrer un commentaire