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.
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.
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
);