我开发了一个couleurs
NPM包,可以设置为将rgb
方法附加到String.prototype
:
> console.log("Hello World!".rgb(255, 0, 0)) // "Hello World!" in red
Hello World!
undefined
> "Hello World!".rgb(255, 0, 0)
'\u001b[38;5;196mHello World!\u001b[0m'
这个工作良好。如何正确地获取索引 i
处字符的 ANSI 颜色/样式?
可能可以使用一些正则表达式来解决,但我不确定这是否真的好(但如果有正确的实现可用,我不反对)... 我更喜欢通过访问 tty 解释的字符来获得颜色/样式的本地化方法。
> function getStyle (input, i) { /* get style at index `i` */ return style; }
> getStyle("Hello World!".rgb(255, 0, 0), 0); // Get style of the first char
{
start: "\u001b[38;5;196m",
end: "\u001b[0m",
char: "H"
}
> getStyle("Hello " + "World!".rgb(255, 0, 0), 0); // Get style of the first char
{
start: "",
end: "",
char: "H"
}
当我们有多种组合样式时,事情变得复杂了:
> console.log("Green and Italic".rgb(0, 255, 0).italic())
Green and Italic
undefined
> getStyle("Green and Italic".rgb(0, 255, 0).italic(), 0);
{
start: "\u001b[3m\u001b[38;5;46m",
end: "\u001b[0m\u001b[23m",
char: "G"
}
> getStyle(("Bold & Red".bold() + " but this one is only red").rgb(255, 0, 0), 0);
{
start: "\u001b[38;5;196m\u001b[1m",
end: "\u001b[22m\u001b[0m",
char: "B"
}
> getStyle(("Bold & Red".bold() + " but this one is only red").rgb(255, 0, 0), 11);
{
start: "\u001b[38;5;196m",
end: "\u001b[0m",
char: "u"
}
> ("Bold & Red".bold() + " but this one is only red").rgb(255, 0, 0)
'\u001b[38;5;196m\u001b[1mBold & Red\u001b[22m but this one is only red\u001b[0m'
如我所说,我正在寻找一种本地方式(可能使用子进程)。
那么,如何获取索引为i
的字符的完整ANSI样式?
map.length
总是undefined
的情况下使用它?我猜我们可以删除与之相关的map
对象和for循环。 - Ionică Bizău