0

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"
1
  • "Result1\\nResult2" didn't worked for you?? Commented Jan 13, 2015 at 2:21

4 Answers 4

2

Escape the backslash with another backslash.

var str = "Result1\\nResult2";
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.