g | x | w | all
Bytes Lang Time Link
076AWK241118T174435Zxrs
nan250921T092205ZMiro Jon
103Python 3.8 prerelease241001T132151ZMalo
117Typst241025T152839ZWallbrea
097Python 3241022T204706Zmovatica
075C241021T124112Zhalperyo
136C#241013T191249ZEzlandin
037Ruby p241010T184216ZJordan
027Vyxal Ḣso240927T231612Zemanresu
030Japt240927T135632ZShaggy
02605AB1E240927T151859ZKevin Cr
135Haskell241001T004636ZAntonio
033Perl 5 + p240930T091109ZDom Hast
083Wolfram Language Mathematica240929T192146Zatt
030Uiua240928T164813Znoodle p
070JavaScript Node.js240928T181603Znoodle p
091C gcc240927T131704Zjdt
099Javascript240928T025352Zl4m2
119JavaScript ES2019240928T040419ZNeil
106PHP 7.4+ 109240928T010145ZIsmael M
073Arturo240927T150056Zchunes

AWK, 91 80 110 79 76 bytes

1~NR{srand()}{for(i=0;i++<NF;)printf"\033[38;5;"int(rand()*99)"m"$i" "}$0=FS

Attempt This Online!

NR<2{srand()}                      # seed only once (or colors repeat)
{for(i=0;i++<NF;){printf           # print each word
"\033[38;5;"int(rand()*99)"m"$i" " # with random color
}}$0=" "                           # new line

enter image description here

Here's my best attempt:

JavaScript, 97 bytes

Uses deprecated element <font> and deprecated methods.

    f=
s=>document.write("<pre>"+s.replace(/\S+/g,m=>m.fontcolor(Math.random().toString(16).slice(-6))))

f("Lorem ipsum dolor sit amet,\n consectetur\tadipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n\nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")

JavaScript, 123 bytes

This version uses the console. It's a bit longer, but doesn't use deprecated methods/elements. Stack Snippets don't seem to support styled output, so here's a live example.

f=
s=>console.log(s.replace(/\S+/g,"%c$&"),...Array(...s.split(/\s+/)).map(_=>"color:#"+Math.random().toString(16).slice(-6)))

Python 3.8 (pre-release), 113 103 bytes

from random import*
def f(s):print(''.join([c+f'\033[{randint(20,36)}m'*c.isspace()for c in' '+s])[1:])

Try it online!

Typst - 117 bytes

#(a=>{show regex("\\S+"):x=>context{text(oklch(50%,99%,(here().position().x/1pt+datetime.today().day())*9deg),x)};a})

It's a function that accepts a string and returns colored content. As far as I know, the only way to have a different output each time is to use the current date.

Call it like this:

#(a=>{show regex("\\S+"):x=>context{text(oklch(50%,99%,(here().position().x/1pt+datetime.today().day())*9deg),x)};a})(
  "Welcome to Code Golf and Coding Challenges Stack Exchange! This is a site for recreational programming competitions, not general programming questions.
Challenges must have an objective scoring criterion, and it is highly recommeded to first post proposed challenges in the Sandbox."
)

result

Python 3, 97 bytes

Using a lookbehind regexp to insert color codes after whitespace.

import random,re
def f(s):print(re.sub(r'^|(?<=\s)',lambda _:f'\033[{random.randint(20,36)}m',s))

Try it online!

C - 80 75 bytes

b,c;main(){while(read(1,&b,1)){c^=b;printf("␛[38;5;%dm%c",b==32?c:-1,b);}}

Try it online!

To compile locally replace with an ANSI escape (0x1b)

Ungolfed

#include <stdio.h>
#include <unistd.h>
char buffer,color;
int main(){
 while(read(1,&buffer,1)){ // read stdin
  color^=buffer; // make color appear random
  printf("\e[38;5;%dm%c",buffer==' ' ? color : -1, buffer);
 }
}

C#, 136 bytes

string a()=>$"\x1B[38;5;{new Random().Next()%16}m";void f(string s){foreach(var c in a()+s)Console.Write(char.IsWhiteSpace(c)?a()+c:c);}

Try it online!

Explanation

string a()=>$"\x1B[38;5;{new Random().Next()%16}m"; // Generates a randomly colored ANSI escape color code

void f(string s)
{
    foreach(var c in a()+s) // For each char c in s, (appending a color code to the start of s)
        Console.Write(char.IsWhiteSpace(c)? a()+c : c); // If whitespace, print color code + c, else c
}

Working example image

Ruby -p, 37 bytes

Contains an unprintable ESC character before the [.

gsub(/\S+/){"[38;5;#{rand 256}m#$&"}

Attempt This Online!

Screenshot of the script in use and its colorful output

Vyxal Ḣso, 27 bytes

‛ß∵øḂ,‡ȧḃḊƛkṄ℅H`<¨² ÷¥=#Π>Π

Try it Online! Indirect -3 thanks to l4m2 for reminding me that font tags exist, -2 thanks to lyxal, -1 thanks to pacman256. Add 3 bytes if handling HTML tags is required. See the revision history for a version with a more balanced colour distribution.

This would be a lot simpler (18 bytes) if only handling spaces was required, but oh well.

‛ß∵øḂ,              # Output "<pre>" (required because newlines)
      ‡--Ḋ          # Group adjacent items by
       ȧ            # Does removing whitespace
        ḃ           # yield an empty string?
          ƛ         # Over each
             ℅      # Choose a random integer
           kṄ       # from 1 to 4096
              H     # in hexadecimal
               `... # Compressed string "<font color=#[color]>[text]"
                    # s flag concatenates this, o flag outputs it
                    # and Ḣ flag renders the result as HTML

enter image description here

Japt, 44 40 30 bytes

Making Japt do things it shouldn't be able to do again!

OlUr"%S+"Èimi"␛[38;2;{3ÆLöÃq';

Try it (open your browser's console)

05AB1E, 33 31 29 28 26 bytes

.γð›}ε7Ý39Sδì˜Ω27ç"ÿ[ÿmÿ"?

-4 bytes thanks to @emanresu

Uses the 16 Windows 10 console colors.

Screenshot (which took a while to make, since apparently there was a Windows-10 patch that disabled ANSI again, so I had to enable it (again) in my Registry..):

enter image description here

Try it online (to see the actual ANSI-escaped output).

Explanation:

.γ             # Adjacent group-by on the (implicit) input-string:
               #  (implicitly push the current character)
  ð›           #  Check whether this character is larger than " "
               #  (aka, not "\t", "\n", nor " ")
 }ε            # After the group-by: map over each substring:
               #  (implicitly push the current substring)
   7Ý          #  Push a list in the range [0,7]
     39S       #  Push pair [3,9]
        δ      #  Apply double-vectorized over both lists:
         ì     #   Prepend
          ˜    #  Flatten the [[30,90],[31,93],...,[39,97]] list
           Ω   #  Pop and push a random integer from this list
   27ç         #  Push 27, and convert it to an ASCII character: ␛
      "ÿ[ÿmÿ"  #  Push this string, where:
               #   - the first `ÿ` is replaced with the ␛
               #   - the second `ÿ` is replaced with the random integer
               #   - the third `ÿ` is replaced with the current substring
             ? #  Pop and output it (without newline)

Haskell, 161, 135 bytes

import System.CPUTime
g f=f.(\(%)i->"\ESC["++shows(30+60*i%2+i%9%8)"m")mod<$>getCPUTime
f=(g(++)<*>).foldMap(g. \c i->c:[i|i<-i,c<'!'])

-26 bytes after looking at jdt's solution, and realizing that every space can have a color code attached without breaking the solution.

demonstration of the program changing words to random colors in console environment.

Try it online!

Perl 5 + -p, 33 bytes

s/\S+/.[38;5;@{[0|rand 256]}m$&/g

Try it online!

Wolfram Language (Mathematica), 83 bytes

StringReplace[a:Except[" "|"	"|"
"]..:>a~Style~RandomColor[]~ToString~StandardForm]

Try it online!

Returns a string colored in Mathematica's built-in format.

Sample run, showing words in different colors

Uiua, 41 38 33 30 bytes

&p⍜⊜□⍚($"\x1b[38;5;_m_"⌈×99⚂)⊸>@ 

Note the trailing space, and that \x1b should be a literal ESC byte, which is included in the SBCS encoding for Uiua, at least as of 0.13.0-dev-2.

Explanation:

⊸>@                  # mask of all characters greater than space
⍜⊜□⍚(                # apply to each island of ones:
  ⌈×99⚂              #   random integer between 1 and 99
  $"\x1b[38;5;_m_")  #   Prepend this ANSI color code to the word
&p                   # print with newline

The ANSI color codes are of the form ESC[38;5;{ID} where ID is a number between 1 and 231 inclusive which correlates to a terminal color. Here, I just used the colors 1 to 99 because it's a byte shorter and we only have to support 16 at a minimum.

Screenshot of the program running:

JavaScript (Node.js), 85 70 bytes

s=>console.log(s.replace(/\S+/g,s=>`␛[38;5;${Math.random()*99|0}m`+s))

Attempt This Online!

The is used as a placeholder for what should be a raw ESC (0x1B) byte, since Stack Exchange doesn't like to render control characters.

C (gcc), 92 91 bytes

x;f(int*s){for(x=srand(s);*s;x=!s++)printf("\e[38;5;%dm%s",x|isspace(*s)?rand()%256:-1,s);}

Demo

-1 byte thanks to ceilingcat!

Javascript, 99 bytes

f=
s=>document.write(`<pre>`+s.replace(/\s|^|(.)/g,(h,c)=>`<font color=${z=c?z:Math.random()*1e6}>`+h))
<textarea id=input1>&lt;font color=#123456&gt; test &lt;/font&gt;</textarea><input type=button onclick=f(input1.value)>

<z>${c} to allow input with <>, later use nop <font> instead

JavaScript (ES2019), 119 bytes

f=
s=>console.log(s.replace(r=/\s*\S+\s*/g,"%c%s"),...s.match(r).flatMap(w=>['color:#'+Math.random().toFixed(3).slice(2),w]))
<input type=button value=Run onclick=f(i.value)><textarea id=i>Test&#9;of
various whitespace</textarea>

Works by logging to the browser's console which should honour tabs and newlines. Colours are random from the selection #000...#999.

PHP 7.4+ - 109 106 bytes

Thanks to Jordan for pointing out that the #RGB format works, and saved me 3 bytes.


An anonymous arrow function that print the HTML containing all the stylized words.
The <pre> is needed to keep the whitespace.

fn($t)=>print('<pre>'.preg_replace_callback('/\S+\s*/',fn($m)=>'<font color=#5'.rand(10,99).">$m[0]",$t))

The idea is simple: randomly generates 89 colors (the minimum required is 16), into a deprecated <font> tag.
I chose to change the green and bçue channels for a decent visual variety in the colors (1 digit for each channel).
Does it's best to keep whitespaces by using the <pre> tag.

As per the rules, HTML output is allowed, and a function is also allowed.

You can try it here:

// This is my code
let answer = "fn($t)=>print('<pre>'.preg_replace_callback('/\\S+\\s*/m',fn($m)=>'<font color=#5'.rand(10,99).\">$m[0]\",$t))";

document.getElementById('code').value = answer;
document.getElementById('code_length').textContent = answer.length;

// Here's the PHP code that will run
let code = `
// Example text
$text = "Write a program or function that takes a string as input and prints or otherwise renders the text with each word in a random color";

// My code
$fn = ${answer};

// Run the code
$fn($text);
`;

run_php(code);

async function run_php(code) {
  const { PhpWeb } = await import('https://cdn.jsdelivr.net/npm/php-wasm/PhpWeb.mjs');
  const php = new PhpWeb;
  
  let out = '';
  
  php.addEventListener('output', (event) => {
    out += event.detail.join('');
  });

  let x = await php.run('<?php ' + code);
  
  document.getElementById('output_text').value = out;
  document.getElementById('output_html').innerHTML = out;
}
body {
  margin: 0;
  padding: 0;
  
  font-family: sans-serif;
}

p {
  margin: 0;
}

#code {
  width: 100vw;
  width: 100dvw;
  
  resize: resize-x;
}

#output_text {
  width: 100vw;
  width: 100dvw;
  
  height: 50vh;
  height: 50dvh;
  
  resize: resize-x;
}

#output_html {
  max-width: 100vw;
  max-width: 100dvw;
  
  overflow: auto;
}
<p>Code: - Length: <span id="code_length">0</span></p>
<textarea id="code"></textarea>
<p>Output:</p>
<textarea id="output_text"></textarea>
<div id="output_html"></div>

Arturo, 73 bytes

$=>[loop match&{\S+|\s+}=>[prints color to :color map 3=>[255 1random]&]]

Try it!

Works in the online playground and most terminals.