Strip ANSI escape sequences

References: https://todo.sr.ht/~emersion/gamja/11
This commit is contained in:
Simon Ser 2020-08-04 14:25:05 +02:00
parent b37dfb77fe
commit 96c890f1f5
No known key found for this signature in database
GPG key ID: 0FDE7BE0E88F5E48
3 changed files with 62 additions and 5 deletions

53
lib/ansi.js Normal file
View file

@ -0,0 +1,53 @@
// See https://modern.ircdocs.horse/formatting.html
const BOLD = "\x02";
const ITALIC = "\x1D";
const UNDERLINE = "\x1F";
const STRIKETHROUGH = "\x1E";
const MONOSPACE = "\x11";
const COLOR = "\x03";
const COLOR_HEX = "\x04";
const REVERSE_COLOR = "\x16";
const RESET = "\x0F";
function isDigit(ch) {
return ch >= "0" && ch <= "9";
}
export function strip(text) {
var out = "";
for (var i = 0; i < text.length; i++) {
var ch = text[i];
switch (ch) {
case BOLD:
case ITALIC:
case UNDERLINE:
case STRIKETHROUGH:
case MONOSPACE:
case REVERSE_COLOR:
case RESET:
break; // skip
case COLOR:
if (!isDigit(text[i + 1])) {
break;
}
i++;
if (isDigit(text[i + 1])) {
i++;
}
if (text[i + 1] == "," && isDigit(text[i + 2])) {
i += 2;
if (isDigit(text[i + 1])) {
i++;
}
}
break;
case COLOR_HEX:
i += 6;
break;
default:
out += ch;
}
}
return out;
}