如何避免在JavaScript模板字符串插值中控制字符解释?
我有一个包含控件字符(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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以删除双引号,并使用
json.stringify
,它也会产生这些引号,并编码Newline字符(例如Tab,bs,bs,ff和Escap double Quote and BackSlash):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):