如何避免在JavaScript模板字符串插值中控制字符解释?

发布于 2025-01-25 10:25:48 字数 780 浏览 3 评论 0原文

我有一个包含控件字符(newline)的字符串变量。我想输出该变量,但以控制字符为文字表示,而不是解释:

console.log(`Using "${nl}" as newline`)

nl变量可能包含\ n\ r <\ n之一/code>,或\ r \ n。 输出当然是

使用
作为newline

,但应该是

使用“ \ r \ n”作为newline

我想我需要以某种方式构造这样的字符串

console.log('Using "\\r\\n" as newline')

,因此我一直在尝试通过使用nl.replace预先准备另一个后斜线来逃脱nl中的后斜线(),但这似乎不起作用,因为nl变量实际上不包含任何反斜击字符。

有没有一种方法可以一般地执行此操作,即不明确编码\ n\ r\ code> \ r \ r \ n

I have a string variable containing a control character (newline). I want to output that variable but with the control character as its literal representation and not interpreted:

console.log(`Using "${nl}" as newline`)

where the nl variable may contain one of \n, \r, or \r\n.
The output of this is of course

Using
as newline

but it should be e.g.

Using "\r\n" as newline

I guess I somehow need to construct a string like this

console.log('Using "\\r\\n" as newline')

So I've been trying to escape the backslashes in nl by prepending another backslash using nl.replace() but that doesn't seem to work because the nl variable doesn't actually contain any backslash characters.

Is there a way to do this generically, i.e. without coding explicitly for \n, \r, and \r\n?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

不打扰别人 2025-02-01 10:25:48

您可以删除双引号,并使用json.stringify,它也会产生这些引号,并编码Newline字符(例如Tab,bs,bs,ff和Escap double Quote and BackSlash):

let nl = "\r\n";
console.log(`Using ${JSON.stringify(nl)} as newline`);

// Or with a newline in a template literal:

nl = `
`;
console.log(`Using ${JSON.stringify(nl)} as newline`);

You could remove the double quotes, and use JSON.stringify which also produces those quotes, and which encodes newline characters (and more, such as TAB, BS, FF, and escapes double quote and backslash):

let nl = "\r\n";
console.log(`Using ${JSON.stringify(nl)} as newline`);

// Or with a newline in a template literal:

nl = `
`;
console.log(`Using ${JSON.stringify(nl)} as newline`);

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