views:

39

answers:

2
<div class="Colorize">
SomeBigWordThatIsFormedFromOtherWords
</div>

is it possible to make each word of a different color, like to transform it into something like this:

    <span style="color:red">Some</span>
    <span style="color:blue">Big</span> etc.
+5  A: 

Yes, you can do like this:

$(function(){
  var colors = [ 'red', 'blue', 'green' ];
  var colorIndex = -1;
  $('.Colorize').each(function(){
    $(this).html($(this).text().replace(/([A-Z][a-z]+)/g,function($0, $1){
      colorIndex++;
      return '<span style="color:' + colors[colorIndex % colors.length] + '">' + $1 + '</span>';
    }));
  });
});
Guffa
modified your answer a little, works now, +1
jAndy
@jAndy: Yes, I did pretty much the same modification at the same time. :)
Guffa
+1  A: 

You may need to modify the regex a little if you ever expect to encounter strings like ChangeThisTheHiglightIBMAsAWord. I can't plug it into jQuery (cos I don't know the syntax) but a C# method would look like this :

public static string SplitCamelCase( string str )
{
    return Regex.Replace( Regex.Replace( str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2" ), @"(\p{Ll})(\P{Ll})", "$1 $2" );
}

Hope someone can plug it all together in a complete solution for you.

ZombieSheep