0

I can't escape a new line when it is in an object. I just did this in Node. Anyone have an idea how this can be done?

var result =  {
    key1: "This is a line\n with new\n lines\n.",
    key2: "No new lines here."
};

Here are my results:

result
Object

var myTemp = JSON.stringify(result);

Here are the results

‌‌ myTemp
‌ {"key1":"This is a line\n with new\n lines\n.","key2":"No new lines here."}

var newTemp = myTemp.replace(/\\n/g, "\\n");

Finally, here are the final results.

‌‌ newTemp
‌ {"key1":"This is a line\n with new\n lines\n.","key2":"No new lines here."}

Notice how it is still \n, not \\n.

Bergi
  • 572,313
  • 128
  • 898
  • 1,281
Matt Kuhns
  • 1,288
  • 1
  • 12
  • 24
  • Why would you want to get `\\n`? That's not an escaped newline, that's an escaped backslash followed by an n character. – Bergi May 15 '17 at 20:42

2 Answers2

0

Your regex needs to be escaped, too: myTemp.replace(/\\n/g, "\n")

Reason:

  • \n matches actual new line characters
  • \\n matches the representation of a new line character given by the characters "\" followed by "n" as it can be found in the JSON string.
le_m
  • 17,771
  • 9
  • 60
  • 73
-1

Based on an answer on StackOverflow here: JavaScript string newline character?

Below is the safest way to escape new lines:

var key1 = "This is a line\n with new\n lines\n.";
var k2 = key1.replace(/\r\n|\r|\n/g,'');
Community
  • 1
  • 1
Yeshodhan Kulkarni
  • 2,648
  • 1
  • 15
  • 19
  • This will actually remove the new line characters entirely, which is not the same as escaping them (almost opposite)! – Kendall Jan 25 '22 at 16:56