I have a string variable containing a control character (newline). I want to output that variable but with the control character as its literal representation and not interpreted:
console.log(`Using "${nl}" as newline`)
where the nl
variable may contain one of \n
, \r
, or \r\n
.
The output of this is of course
Using
as newline
but it should be e.g.
Using "\r\n" as newline
I guess I somehow need to construct a string like this
console.log('Using "\\r\\n" as newline')
So I've been trying to escape the backslashes in nl
by prepending another backslash using nl.replace()
but that doesn't seem to work because the nl
variable doesn't actually contain any backslash characters.
Is there a way to do this generically, i.e. without coding explicitly for \n
, \r
, and \r\n
?
CodePudding user response:
You could remove the double quotes, and use JSON.stringify
which also produces those quotes, and which encodes newline characters (and more, such as TAB, BS, FF, and escapes double quote and backslash):
let nl = "\r\n";
console.log(`Using ${JSON.stringify(nl)} as newline`);
// Or with a newline in a template literal:
nl = `
`;
console.log(`Using ${JSON.stringify(nl)} as newline`);