Skip to content

Instantly share code, notes, and snippets.

@max1mde
Created July 16, 2024 17:20
Show Gist options
  • Save max1mde/f2ec4a1020f1a208e061d1d67b5ea446 to your computer and use it in GitHub Desktop.
Save max1mde/f2ec4a1020f1a208e061d1d67b5ea446 to your computer and use it in GitHub Desktop.
Convert html like tags in text to a working colored text working discord (in a code block ```ansi <text>```)

Example text:

<red>Red text</red> <green>Green text</green> <yellow>Yellow text</yellow> <blue>Blue text</blue> <pink>Pink text</pink> <teal>Teal text</teal> <white>White text</white> <gray>Gray text</gray> <orange-bg>Orange background</orange-bg> <gray3-bg>Gray3 background</gray3-bg> <gray2-bg>Gray2 background</gray2-bg> <gray1-bg>Gray1 background</gray1-bg> <blue-bg>Blue background</blue-bg> <gray-bg>Gray background</gray-bg> <white-bg>White background</white-bg> <darkblue-bg>Dark blue background</darkblue-bg> <b>Bold text</b> <u>Underlined text</u> <br>New line<br>Another line

Gets converted to:

image

function convertToAnsiFormatting(text) {
const colorMap = {
red: "31",
green: "32",
yellow: "33",
blue: "34",
pink: "35",
teal: "36",
white: "37",
gray: "30",
};
const bgColorMap = {
"orange-bg": "41",
"gray4-bg": "42",
"gray3-bg": "43",
"gray2-bg": "44",
"blue-bg": "45",
"gray1-bg": "46",
"white-bg": "47",
"dark-bg": "40",
};
const styleMap = {
b: "1",
u: "4",
};
text = text.replace(/<(\w+(-bg)?)>/g, (match, p1) => {
if (colorMap[p1]) return `\x1b[${colorMap[p1]}m`;
if (bgColorMap[p1]) return `\x1b[${bgColorMap[p1]}m`;
if (styleMap[p1]) return `\x1b[${styleMap[p1]}m`;
return match;
});
text = text.replace(/<\/\w+(-bg)?>/g, "\x1b[0m");
text = text.replace(/<r>/g, "\x1b[0m");
text = text.replace(/<br>/g, "\n");
return text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment