How to use \n in a javascript string

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

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

8

3 Answers

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

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

Here are all the string escape codes:

  • \0 The NUL character (\u0000)
  • \b Backspace (\u0008)
  • \t Horizontal tab (\u0009)
  • \n Newline (\u000A)
  • \v Vertical tab (\u000B)
  • \f Form feed (\u000C)
  • \r Carriage return (\u000D)
  • \" Double quote (\u0022)
  • \' Apostrophe or single quote (\u0027)
  • \\ Backslash (\u005C)
  • \x XX The Latin-1 character specified by the two hexadecimal digits XX
  • \u XXXX The Unicode character specified by the four hexadecimal digits XXXX
0

Escape \n with \\n and store the string in DB. However, only \n can also be stored in DB.

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

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like