【问题标题】:How to write special characters in template literals?如何在模板文字中写入特殊字符?
【发布时间】:2021-04-06 03:33:18
【问题描述】:

我在 javascript 中为字符串使用模板文字,并希望像在普通字符串中一样插入带有十六进制代码 (&lettersandnumbers;) 的特殊字符,如 & 和 $,但它不会读取它。我尝试将其放入 ${} 中,但这也无济于事。有办法写吗?

【问题讨论】:

  • &lettersandnumbers; 用于 HTML 标记,而不用于 JavaScript 字符串文字(除非字符串文字稍后与 innerHTML 一起插入 HTML 或类似的东西)
  • 当然,例如\u{42F} 给你Я

标签: javascript template-literals


【解决方案1】:

请参阅 MDN 上的 Escape notation

Code Output
\0 U+0000 NULL character
' single quote
" double quote
\ backslash
\n new line
\r carriage return
\v vertical tab
\t tab
\b backspace
\f form feed
\uXXXX (where XXXX is 4 hex digits; range of 0x0000–0xFFFF) UTF-16 code unit / Unicode code point between U+0000 and U+FFFF
\u{X} ... \u{XXXXXX} (where X…XXXXXX is 1–6 hex digits; range of 0x0–0x10FFFF) UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF
\xXX (where XX is 2 hex digits; range of 0x00–0xFF) ISO-8859-1 character / Unicode code point between U+0000 and U+00FF

【讨论】:

    【解决方案2】:

    您可以使用转义字符(反斜杠 - \)将特殊字符视为普通字符。

    const text = `text\$somemoretext\&end`;
    console.log(text);

    【讨论】:

      【解决方案3】:

      &lettersandnumbers; 转义序列用于 HTML,而不是 JavaScript 字符串。在 javascript 字符串中,有不同的方式来表示特殊字符。在您的情况下,您不需要转义字符“$”或“&”。

      要使用十六进制代码表示字符串中的字符,请执行以下操作:`I like \x24\x24\x24!`,其计算结果为“我喜欢 $$$!”。

      【讨论】:

        猜你喜欢
        • 2012-03-25
        • 1970-01-01
        • 2018-09-29
        • 2015-01-05
        • 2013-12-09
        • 1970-01-01
        • 2023-03-06
        • 2021-05-26
        • 2021-01-18
        相关资源
        最近更新 更多