如何在 javascript 字符串中使用 \n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48692039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:12:03  来源:igfitidea点击:

How to use \n in a javascript string

javascriptstringarangodbconsole.log

提问by EZ-C

Example:

例子:

var i = 'Hello \n World'
console.log(i)

Would return:

会返回:

Hello
World

and I want it to return

而且我希望它返回

Hello \n World

not rendering the new line, as I intend to store this in a database.

不呈现新行,因为我打算将其存储在数据库中。



FOR THOSE WHO WANT TO STORE \n in Database

对于那些想要在数据库中存储 \n 的人

You don't need to escape, as your Document Database will do JSON.stringify, I use ArangoDB and it works perfectly fine, thanks to @PaulPro

你不需要逃避,因为你的文档数据库会做 JSON.stringify,我使用 ArangoDB 并且它工作得很好,感谢@PaulPro

回答by Scott Marcus

You would escape the \with \\, which would tell the interpreter just to produce the character without processing it as a special character:

您将转义\with \\,它会告诉解释器只生成字符而不将其作为特殊字符处理:

var i = 'Hello \n World';
console.log(i)

Here are all the string escape codes:

以下是所有字符串转义码:

  • \0The NUL character (\u0000)
  • \bBackspace (\u0008)
  • \tHorizontal tab (\u0009)
  • \nNewline (\u000A)
  • \vVertical tab (\u000B)
  • \fForm feed (\u000C)
  • \rCarriage return (\u000D)
  • \"Double quote (\u0022)
  • \'Apostrophe or single quote (\u0027)
  • \\Backslash (\u005C)
  • \x XXThe Latin-1 character specified by the two hexadecimal digits XX
  • \u XXXXThe Unicode character specified by the four hexadecimal digits XXXX
  • \0NUL 字符 (\u0000)
  • \b退格 (\u0008)
  • \t水平标签 (\u0009)
  • \n换行符 (\u000A)
  • \v垂直制表符 (\u000B)
  • \f换页 (\u000C)
  • \r回车 (\u000D)
  • \"双引号 (\u0022)
  • \'撇号或单引号 (\u0027)
  • \\反斜杠 (\u005C)
  • \x XX由两个十六进制数字 XX 指定的 Latin-1 字符
  • \u XXXX四位十六进制数字XXXX指定的Unicode字符

回答by Ammara Laeeq

Escape \nwith \\nand store the string in DB. However, only \ncan also be stored in DB.

逃生\n\\n并存储在数据库中的字符串。但是,\n也只能存储在DB中。

回答by v_vista

Use "\\n" instead of "\n" for this to work, same case with selenium java

使用 "\\n" 而不是 "\n" 使其工作,与 selenium java 相同的情况

      WebElement searchBox = driver.findElement(By.name("q"));
      searchBox.sendKeys("Test \n");
      searchBox.submit();