Search code examples
javascriptstringarangodbconsole.log

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


Solution

  • 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