简体   繁体   中英

How can I use colors in ES6 template strings?

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

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

With ES6 template strings, I get the error:

SyntaxError: Octal literals are not allowed in template strings.

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

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.

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

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

which would be the same as

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

The "\\u{1b}" or "\" 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).

Further reading:

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

it worked for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM