Currently, I'm writing an irc client for myself in node.js, as sort of a proving ground to learning the ins and outs of it. I came to a point where I needed to parse the control codes into HTML, and here's what I came up with.
First, the styles for the color codes..
/*control codes*/
.bg0 { background-color: white; }
.bg1 { background-color: black; }
.bg2 { background-color: navy; }
.bg3 { background-color: green; }
.bg4 { background-color: red; }
.bg5 { background-color: brown; }
.bg6 { background-color: purple; }
.bg7 { background-color: orange; }
.bg8 { background-color: yellow; }
.bg9 { background-color: lime; }
.bg10 { background-color: teal; }
.bg11 { background-color: lightcyan; }
.bg12 { background-color: blue; }
.bg13 { background-color: pink; }
.bg14 { background-color: grey; }
.bg15 { background-color: lightgrey; }
.fg0 { color: white; }
.fg1 { color: black; }
.fg2 { color: navy; }
.fg3 { color: green; }
.fg4 { color: red; }
.fg5 { color: brown; }
.fg6 { color: purple; }
.fg7 { color: orange; }
.fg8 { color: yellow; }
.fg9 { color: lime; }
.fg10 { color: teal; }
.fg11 { color: lightcyan; }
.fg12 { color: blue; }
.fg13 { color: pink; }
.fg14 { color: grey; }
.fg15 { color: lightgrey; }
Here is the mircToHtml() js function. I use and since they will span multiple elements.
//mircToHtml() by PennyBreed @ irc.nuphrax.com
//----------------------------------------------
function mircToHtml(text) {
//control codes
var rex = /\003([0-9]{1,2})[,]?([0-9]{1,2})?([^\003]+)/,matches,colors;
if (rex.test(text)) {
while (cp = rex.exec(text)) {
if (cp[2]) {
var cbg = cp[2];
}
var text = text.replace(cp[0],'<span class="fg'+cp[1]+' bg'+cbg+'">'+cp[3]+'</span>');
}
}
//bold,italics,underline (more could be added.)
var bui = [
[/\002([^\002]+)(\002)?/, ["<b>","</b>"]],
[/\037([^\037]+)(\037)?/, ["<u>","</u>"]],
[/\035([^\035]+)(\035)?/, ["<i>","</i>"]]
];
for (var i=0;i < bui.length;i++) {
var bc = bui[i][0];
var style = bui[i][1];
if (bc.test(text)) {
while (bmatch = bc.exec(text)) {
var text = text.replace(bmatch[0], style[0]+bmatch[1]+style[1]);
}
}
}
return text;
}
It's best to wrap the result in a div, or some other element to ensure broken tags don't leak out into your other HTML. Here's a working jsfiddle: http://jsfiddle.net/t5Abt/2/