如何在 ES6 模板字符串中使用颜色?

How can I use colors in ES6 template strings?

在 ES5 及以下版本中,我可以在 JS 字符串中使用 ANSI 颜色,例如

"3[31m Hello World3[0m".

使用 ES6 模板字符串时,出现错误:

SyntaxError: Octal literals are not allowed in template strings.

我试过\u{31m},但也没用。

根据 standard,"strict mode" 中不处理八进制转义。标准中没有给出基本原理,但重复使用术语 "legacy" 和 "octal" 可能是试图说服 reader 该标准的唯一目的是为了使用 UTF-8 的网络浏览器。

您对 \u{31m} 的试验偏离了目标:大括号围绕 十六进制数字 。你的意思可能看起来像这样:

"\u{1b}[31m Hello World\u{1b}[0m"

相同
"\u001b[31m Hello World\u001b[0m"

"\u{1b}""\u001b" 是转义符(参见 ECMA-35 和 ECMA-48),不可打印。字符串中的其他字符是可打印的(并且不必转义)。

进一步阅读:

\033[31m --> \x1b[31m

对我有用