Example:
var i = 'Hello \n World'
console.log(i)Would return:
Hello
Worldand I want it to return
Hello \n Worldnot 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
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:
\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
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();