非常简单的问题,但出于某种原因,我在谷歌搜索了10分钟后仍然找不到答案。 我该如何在JavaScript中打印时显示转义字符?
例子:
例子:
str = "Hello\nWorld";
console.log(str);
提供:
Hello
World
当我希望它给出:
Hello\nWorld
str = "Hello\nWorld";
console.log(str);
提供:
Hello
World
当我希望它给出:
Hello\nWorld
str = "Hello\nWorld";
并以字符串文字形式输出其包含的内容(一个相当特定的用例),您可以使用JSON.stringify
:
console.log(JSON.stringify(str)); // ""Hello\nWorld""
const str = "Hello\nWorld";
const json = JSON.stringify(str);
console.log(json); // ""Hello\nWorld""
for (let i = 0; i < json.length; ++i) {
console.log(`${i}: ${json.charAt(i)} (0x${json.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")})`);
}
.as-console-wrapper {
max-height: 100% !important;
}
console.log
(至少在Chrome的实现中)会添加外部引号,但其中的内容是一个字符串字面量(是的,有点令人困惑)。
JSON.stringify
接受你提供的内容(在这种情况下是一个字符串),并返回一个包含该值的有效JSON的字符串。所以对于上面的例子,它返回一个开引号("
),单词Hello
,一个反斜杠(\
),字母n
,单词World
,和一个闭引号("
)。字符串中的换行符在输出中被转义为\
和n
,因为这是在JSON中编码换行符的方式。其他转义序列也以类似的方式编码。
H
、e
、l
、l
、o
、\
、n
、W
、o
、r
、l
、d
的字符串,你不需要使用 JSON.stringify
。只需转义反斜杠,使其不被视为转义字符:"Hello\\nWorld"
console.log("Hello\\nWorld");
JSON.stringify
这个东西只是用于在字符串中包含换行符等内容时,以类似字符串文字的输出形式显示,通常用于调试。"asdasd\Sasdasd"
应为"asdasdSasdasd"
。当您转义一个没有特殊含义的字符时,结果就是该字符本身。换句话说,"\S".length
的长度为1,因为它定义了一个包含S的单字符字符串,就像"S"
一样。 - T.J. Crowder\
就消失了,因为它没有意义。如果您使用模板文字,可以使用String.raw
标记的模板函数:String.raw \
\S`(请注意,这些是反引号,而不是引号),返回
"\S"`。 - T.J. Crowder\xA0
或\u00A0
,但作为字面字符也是完全有效的。 - T.J. Crowder
String.raw\
Hello\nWorld``,但是这个问题被错误地标记为重复。 - Somo S.