如何在插值字符串中使用Newlines中使用Newline字符?
我遇到问题,将newline字符添加到已经具有新线的字符串中。
例如:
const foo = "test\ntest";
const string = `mutation {
some_field: "${foo}"
}`;
这将被输出为:
mutation {
some_field: "test
test"
}
但是我希望它输出为:
mutation {
some_field: "test\ntest"
}
保留现有的白空间/新线的位置,但您可以在其中添加“ test \ ntest”之类的字符串。当前的线路破坏导致语法错误。
我尝试以各种不同的方式将这些字符串添加在一起,但我不知道如何强制\ n
在字段值中保留\ n
。
I am having issues adding newline characters into a string that already has newlines.
For example:
const foo = "test\ntest";
const string = `mutation {
some_field: "${foo}"
}`;
This will be output as:
mutation {
some_field: "test
test"
}
But I want it to output as:
mutation {
some_field: "test\ntest"
}
Where the existing white-space/newlines are preserved but you can add a string like "test\ntest"
inside of it. This current line-breaking is causing syntax errors.
I have tried adding together these strings in various different ways but I can't figure out how to force \n
to remain \n
in the field value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在JavaScript字符串文字中具有\ n时,它代表了一个newline字符,而不是后斜切,其次是n。如果您想要后斜线,然后是n,则必须带有另一个后斜切角色逃脱后斜切角色。也就是说,您必须将\ n放在字符串文字中。
When you have \n in a JavaScript string literal, it represents a newline character, not a backslash followed by n. If you want a backslash followed by n, you have to escape the backslash character with another backslash character. That is, you have to put \n in the string literal.
您需要通过逃脱后挡板将文字
\ n
放在字符串中。但这似乎充满了危险。您几乎应该肯定会使用JSON,而不是模板字面的。
You need to put literal
\n
in the string by escaping the backslash.But this seems like it's fraught with danger. You should almost certainly be using JSON, not a template literal.