如何在插值字符串中使用Newlines中使用Newline字符?

发布于 2025-02-11 23:44:01 字数 484 浏览 0 评论 0原文

我遇到问题,将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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

骷髅 2025-02-18 23:44:01

当您在JavaScript字符串文字中具有\ n时,它代表了一个newline字符,而不是后斜切,其次是n。如果您想要后斜线,然后是n,则必须带有另一个后斜切角色逃脱后斜切角色。也就是说,您必须将\ n放在字符串文字中。

const foo = "test\\ntest";
const string = `mutation {
   some_field: "${foo}"
}`;

console.log(string)

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.

const foo = "test\\ntest";
const string = `mutation {
   some_field: "${foo}"
}`;

console.log(string)

满栀 2025-02-18 23:44:01

您需要通过逃脱后挡板将文字\ n放在字符串中。

const foo = "test\\ntest";
const string = `mutation {
   some_field: "${foo}"
}`;

console.log(string);

但这似乎充满了危险。您几乎应该肯定会使用JSON,而不是模板字面的。

const foo = "test\ntest";
const string = `mutation ${JSON.stringify({
   some_field: foo
}, null, 4)}`;

console.log(string);

You need to put literal \n in the string by escaping the backslash.

const foo = "test\\ntest";
const string = `mutation {
   some_field: "${foo}"
}`;

console.log(string);

But this seems like it's fraught with danger. You should almost certainly be using JSON, not a template literal.

const foo = "test\ntest";
const string = `mutation ${JSON.stringify({
   some_field: foo
}, null, 4)}`;

console.log(string);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文