0

So I wanted to make every word in the text different color, but I've only find code to make every letter in the text a different color. Is there any way to turn this to change color in every word instead every letter?

<script type="text/javascript">
       var message = "The quick brown fox.";
       var colors = new Array("#ff0000","#00ff00","#0000ff"); // red, green, blue
       for (var i = 0; i < message.length; i++)
          document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + message[i] + "</span>");
    </script>
Simone-Cu
  • 1,109
  • 8
  • 21
MSmS
  • 189
  • 1
  • 4
  • 15
  • 3
    Imho split the message by whitespace and loop the array. – YvesR Sep 29 '12 at 12:52
  • Yes, the answer is to split the string into an array of words. See this also this post: http://stackoverflow.com/questions/2817646/javascript-split-string-on-space-or-on-quotes-to-array – Simone-Cu Sep 29 '12 at 12:55

4 Answers4

2

Small change required.

Split the message into an array by space (" ")

   var message = "The quick brown fox.";
   var messageArr = message.split(" ");
   var colors = ["#ff0000","#00ff00","#0000ff"]; // red, green, blue
   for (var i = 0; i < messageArr .length; i++)
   {
      document.write("<span style='color:" + colors[(i % colors.length)] + ";'>" + messageArr[i] + " </span>");
   }

See it on this JSFiddle

Note: I've also changed your colors array definition to using the array literal notation [], which is a slightly better way of declaring an array.

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
1
var message = "The quick brown fox.",
    words   = message.split(/\s+/),
    colors  = ['#ff0000', '#00ff00', '#0000ff'];

for (var i = 0; i < words.length; i++) {
    document.write('<span style="color: ' + colors[(i % colors.length)] + ';">' + words[i] + '</span>');
}
Björn
  • 29,019
  • 9
  • 65
  • 81
1
var text = "Glee is very very awesome!";
text = text.split(" ");
var colors = ["red", "green", "rgb(0, 162, 232)"]; //you can use color names, as well as RGB notation
var n = colors.length; //no need to re-grab length each time
for(var i = 0; i < text.length; i ++) {
    document.write('<span style = "color: ' + colors[i % n] + '">' + text[i] + '</span>');
}

Little demo: little link.

Chris
  • 26,544
  • 5
  • 58
  • 71
0

Let's try some different way. The live demo.

var message = "The quick brown fox.",
    colors = ["#ff0000","#00ff00","#0000ff"],
    i = 0, len = colors.length;

message = message.replace(/\b(\w+)\b/g, function (match, word) {
    return '<span style="color: ' + colors[(i++ % len)] + ';">' + word + '</span>';
});
document.write(message);
​
xdazz
  • 158,678
  • 38
  • 247
  • 274