0

So I have a string:

var s = "foo\nbar\nbob";

I want the string to become:

"foo\\nbar\\nbob"

How can I replace every \n with a \\n?

I've tried using some for loops, but I can't figure it out.

Matt X
  • 224
  • 1
  • 6
  • 17
  • `\n` in a string is a literal newline (one character). Do you mean that you want literal newlines to be preceded by a single backslash? – CertainPerformance Nov 09 '18 at 00:43
  • @CertainPerformance yes – Matt X Nov 09 '18 at 00:44
  • I feel like this question screams "why are you doing this?" before you end up shooting yourself in the foot somewhere else. – Adam Jenkins Nov 09 '18 at 00:45
  • Then you want it to become `"foo\\\nbar\\\nbob"`? – Ruan Mendes Nov 09 '18 at 00:45
  • @Adam can you please explain to me why you think that? I will explain why I need this after. – Matt X Nov 09 '18 at 00:48
  • @MattX - to be clear, I'm not saying that doing exactly what you asked is wrong in any way, but it does "smell" like you are trying to "fix" something that should be fixed another way. Again, it might end up that using JS to do what you want might be the only way, but it's not clear. – Adam Jenkins Nov 09 '18 at 01:06
  • @Adam so, I discovered that \n cant be in json, for it messes with the json source, not the json data itself. This was the only thing that I could think about how to fix this. If there is a better way, please let me know Asap – Matt X Nov 09 '18 at 01:08
  • @MattX What do you mean by "it can't be in json"? – Dave Newton Nov 09 '18 at 01:11
  • @MattX what's generating the JSON? – Adam Jenkins Nov 09 '18 at 01:11
  • @DaveNewton You can't have \n in a string and then try and parse it to json. – Matt X Nov 09 '18 at 01:12
  • @Adam I have some raw json in a string with \n(s) in the data. JSON.parse(str) throws errors, so I thought that I could turn all of the \n into \\n and then parse the JSON. – Matt X Nov 09 '18 at 01:13
  • @MattX - I'm still curious as to the source (e.g. the server) of the JSON. If you have control over the serverside code that's generating the JSON, then I'd do the escaping there. Either way, now this question is a dupe: https://stackoverflow.com/questions/42068/how-do-i-handle-newlines-in-json – Adam Jenkins Nov 09 '18 at 01:17

1 Answers1

1

A simple .replace would work - search for \n, and replace with \\n:

var s = "foo\nbar\nbob";
console.log(
  s.replace(/\n/g, '\\\n')
  //                ^^ double backslash needed to indicate single literal backslash
);

Note that this results in "a single backslash character, followed by a literal newline character" - there will not be two backslashes in a row in the actual string. It might be a bit less confusing to use String.raw, which will interpret every character in the template literal literally:

var s = "foo\nbar\nbob";
console.log(
s.replace(/\n/g, String.raw`\
`) // template literal contains one backslash, followed by one newline
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320