I want to display strings exactly as they are, without special characters (i.e. d
, n
, s
) being recognized.
For example, say I have this string with a newline character:
let someString = 'hellonthere';
I need to escape the newline character, so I need to replace the backslash with 2 backslashes to get hello\nthere
.
Solution Attempt 1:
let replacedString = someString.replace(/\/g, "\\"),
but replacedString
still recognizes the newline character:
hello
there
when what I want to see for replacedString
is hello\nthere
.
Solution Attempt 2:
let rawString = String.raw`hellonworld`.replace(/\/g,"\\");
This works well, because rawString
is hello\nworld
. However, the template literal part should be a variable (someString
) and when I include someString
like so:
let rawString = String.raw`${someString}`.replace(/\/g,"\\");
I get this for rawString
:
hello
there
How do I simply replace a backslash with 2 backslashes? I’ve already scoured several posts on Stack Overflow and can’t seem to find a solution to this problem.
Thanks in advance!