In JavaScript, I have strings including newlines such as var s = "123\n456" or var s = "123\r\n456".
Using console.log(s), the dev tools of a browser displays real newlines in console.
I would like to know how to print literally the string. For instance, I want to see 123\n456 or 123\r\n456 in dev tools or a browser.
Could anyone help?
you could console.log(JSON.stringify(s))
You can easily display the raw string using String.raw and a template literal
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw
const rawString = String.raw`Hello\nHow do you do?`;
console.log(rawString);
If you can not directly use a template literal, you can convert the string into a template literal, and then proceed. Note my linked method includes eval which can be a security risk depending on use.
i.e.
const myString = "Hello\nWorld";
const myRawString = eval("String.raw`"+myString+"`");