Switching \n with \\n in javascript

3136 views javascript

So I have a string:

var s = "foo\nbar\nbob";

I want the string to become:


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

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

answered question

\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 yes

I feel like this question screams "why are you doing this?" before you end up shooting yourself in the foot somewhere else.

Then you want it to become "foo\\\nbar\\\nbob"?

@Adam can you please explain to me why you think that? I will explain why I need this after.

1 Answer


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

var s = "foo\nbar\nbob";
  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";
s.replace(/\n/g, String.raw`\
`) // template literal contains one backslash, followed by one newline

posted this

Have an answer?


Please login first before posting an answer.