Javascript - 如何在字符串中显示转义字符? [英] Javascript - How to show escape characters in a string?

查看:94
本文介绍了Javascript - 如何在字符串中显示转义字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单的问题,但由于某些原因,我无法在10分钟的谷歌搜索后找到答案。例如:

  str =Hello\\\
World;
console.log(str);

提供:

 code> Hello 
World

当我想要:

  Hello \\\
World


解决方案

如果您的目标是

  str =Hello\ nWorld;并输出字符串文字形式中包含的内容,您可以使用 JSON。 stringify 

  console.log(JSON.stringify(str)); //Hello \\\
world

console.log 添加外部引号(至少在Chrome的实现中),但其中的内容是字符串字面值。


Very simple question, but for some reason I can't find the answer anywhere after 10 minutes of Googling. How can I show escape characters when printing in Javascript?

Example:

str = "Hello\nWorld";
console.log(str);

Gives:

Hello
World

When I want it to give:

Hello\nWorld

解决方案

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nworld""

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal.

这篇关于Javascript - 如何在字符串中显示转义字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆