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

时间:2022-12-22 19:35:57

In ES5 and below, I could use ANSI colors in JS strings such as

在ES5和下面,我可以在JS字符串中使用ANSI颜色,比如

"\033[31m Hello World\033[0m".

“033年\[31 033 Hello World \[0 m”。

With ES6 template strings, I get the error:

使用ES6模板字符串,我得到错误:

SyntaxError: Octal literals are not allowed in template strings.

I have tried \u{31m} but it didn't work either.

我试过了\u{31m},但也不管用。

1 个解决方案

#1


4  

According to the standard, octal escapes are not handled in "strict mode". There is no rationale given in the standard, but probably the repetitive use of the term "legacy" in conjunction with "octal" is an attempt to persuade the reader that the only purpose of this standard is for web browsers using UTF-8.

按照标准,八进制转义不在“严格模式”中处理。该标准没有给出任何理由,但可能重复使用术语“遗留”与“八进制”是试图说服读者,该标准的唯一目的是用于使用UTF-8的web浏览器。

Your trial with \u{31m} was off target: the curly braces are around hexadecimal digits. What you probably meant would look like this:

您的测试与\u{31m}关闭了目标:花括号在十六进制数字附近。你可能的意思是:

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

which would be the same as

哪个是相同的?

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

The "\u{1b}" or "\u001b" is the escape character (see ECMA-35 and ECMA-48), and is not printable. The other characters in the string are printable (and do not have to be escaped).

“\u{1b}”或“\u001b”是转义字符(参见ECMA-35和ECMA-48),不能打印。字符串中的其他字符是可打印的(不需要转义)。

Further reading:

进一步阅读:

#1


4  

According to the standard, octal escapes are not handled in "strict mode". There is no rationale given in the standard, but probably the repetitive use of the term "legacy" in conjunction with "octal" is an attempt to persuade the reader that the only purpose of this standard is for web browsers using UTF-8.

按照标准,八进制转义不在“严格模式”中处理。该标准没有给出任何理由,但可能重复使用术语“遗留”与“八进制”是试图说服读者,该标准的唯一目的是用于使用UTF-8的web浏览器。

Your trial with \u{31m} was off target: the curly braces are around hexadecimal digits. What you probably meant would look like this:

您的测试与\u{31m}关闭了目标:花括号在十六进制数字附近。你可能的意思是:

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

which would be the same as

哪个是相同的?

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

The "\u{1b}" or "\u001b" is the escape character (see ECMA-35 and ECMA-48), and is not printable. The other characters in the string are printable (and do not have to be escaped).

“\u{1b}”或“\u001b”是转义字符(参见ECMA-35和ECMA-48),不能打印。字符串中的其他字符是可打印的(不需要转义)。

Further reading:

进一步阅读: