Reputation: 16629
I want to send
var str = "Result1\nResult2";
\n
servers as a separator.
However, this translates to
"Result1
Result2"
when sent. How can I get
"Result1\nResult2"
Upvotes: 0
Views: 1274
Reputation: 1009
Strings in many languages (including JavaScript), have a feature called escaping which allows you to embed certain blank characters for formatting and control purposes. The way you access them is with the backslash followed by a series of other characters ("\n"
means newline, "\t"
means tab, etc. Here's some info about JavaScript strings https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String). If you just want a backslash character you can use "\\"
which is interpreted as a single backslash. If you wanted backslash followed by n you would have "\\n"
— as many others have pointed out.
That being said, I wouldn't recommend you ever use "\\n"
as a separator given that many programmers would see "\n"
and immediately think newline. You could use the newline character itself "\n"
as the separator (i.e., each item on its own line). Otherwise, if it is possible commas would probably be the best option.
Upvotes: 1
Reputation: 7270
If you're trying to catch it with RegEx, or something similar, that will still catch \n
even if it displays as two lines. If you must have it as a literal, you can escape the backslash.
E.g.
var str = "Result1\\nResult2";
Here's a bit of a visual example using the RegEx search in Atom.
The highlighted part is the selection. As you can see, a new line character is selected when performing a RegEx search using \n
, regardless of if it's actually shown as \n
.
Upvotes: 1
Reputation: 1442
The backslash (\) is an escape character in Javascript as in other languages such as C. This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).
In order to output a literal backslash, you need to escape it. Having said that, below is what you needs to do:
var str="Result1\nResult2"
Upvotes: 0
Reputation: 4091
Escape the backslash with another backslash.
var str = "Result1\\nResult2";
Upvotes: 2