The use of double bars ( \n
, \r
etc) is usually only necessary when dealing with a string representing another string:
var texto1 = "foo\nbar"; // foo
// bar
var texto2 = "'foo\nbar'"; // 'foo
// bar'
var texto3 = "'foo\nbar'"; // 'foo\nbar'
This is the same reason why languages without a regular expression literal (like Java) - or functions / constructors that create a regex from a string - need the double bars:
var regex1 = /(.)/; // Regex: (.)
// Valida "xx": sim
var regex2 = new RegExp("(.)"); // Regex: (.)
// Valida "xx": não
var regex3 = new RegExp("(.)\1"); // Regex: (.)
// Valida "xx": sim
In the case of a JSON contained in a string, therefore, it is required:
var json1 = '{ "texto":"foo\nbar" }'; // { "texto":"foo
// bar" }
var json2 = '{ "texto":"foo\nbar" }'; // { "texto":"foo\nbar" }
But if that JSON was read from a file, no, because the backslash will be included directly in the string (and not interpreted anyway as an escape character).
I know this does not directly answer your question (since it was already determined in the comments that your problem was when displaying the text using HTML), but I hope it helps to illustrate why in some situations it uses \n
and other \n
: in the first you are "escaping" n
, in the other you are escaping own \
(and keeping n
intact).