Here's a couple:
oldie but a goodie
String.prototype.pad
- allows you to specify a character (c) and pad a string to a certain length (n) with that characteruseless but funCode:String.prototype.pad = function(c, n) {
var result=this;
while(result.length<n) {
result=c+result;
}
return result;
}
String.prototype.toRainbow
- returns HTML code for a rainbow version of the string by placing each letter in a differently colored span. Note: it would be pretty easy to modify this to create DOM nodes to be dynamically added into a document. The way it is now, you'd have to use either document.write or the hated innerHTML.Code:String.prototype.toRainbow = function() {
var result="";
var mode=0;
var msg=this;
var rr=0;
var gg=0;
var bb=255;
ink=765/msg.length; //this ensures the whole string will go from blue to red to green back to blue
for(var i = 0; i < msg.length; i++) {
var theColor=Math.round(rr).toString(16).pad("0", 2)+""
+Math.round(gg).toString(16).pad("0", 2)+""
+Math.round(bb).toString(16).pad("0", 2);
result+="<span style=\"color:#"+theColor+"\">"+msg.charAt(i)+"<\/span>";
switch(mode) {
case 0: //blue to red
bb-=ink;
rr+=ink;
if(rr>=255) {
rr=255;
bb=0;
mode=(mode+1)%3;
}
break;
case 1: //red to green
rr-=ink;
gg+=ink;
if(gg>=255) {
gg=255;
rr=0
mode=(mode+1)%3;
}
break; //green to blue
case 2:
gg-=ink;
bb+=ink;
if(bb>=255) {
bb=255;
gg=0;
mode=(mode+1)%3;
}
break;
}
}
return result;
}
