jquery: MakeWordsInThisBigWordWithDifferentColors
<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.
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>';
}));
});
});
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.
精彩评论