Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 427
itsezc Avatar asked Feb 08 '18 18:02

itsezc


People also ask

Can we use \n in string?

Adding Newline Characters in a String In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do I add a new line to a string in HTML?

In HTML, the <br> element creates a line break. You can add it wherever you want text to end on the current line and resume on the next.

How can you break the JavaScript code into different lines?

There are two ways to break JavaScript code into several lines: We can use the newline escape character i.e “\n”. if we are working on the js file or not rendering the code to the html page. We can use the <br> tag.

What is \r in JavaScript string?

The \r metacharacter matches carriage return characters.


2 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
like image 180
Scott Marcus Avatar answered Nov 03 '22 07:11

Scott Marcus


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

like image 38
Ammara Laeeq Avatar answered Nov 03 '22 05:11

Ammara Laeeq