1

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?

SoftTimur
  • 5,630
  • 38
  • 140
  • 292
  • What console is showing them literally? Most browser consoles show a string-literal-like display (that is, with `\n` in it). – T.J. Crowder Sep 10 '21 at 16:54

2 Answers2

4

you could console.log(JSON.stringify(s))

Vulwsztyn
  • 2,140
  • 1
  • 12
  • 20
0

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+"`");
async await
  • 1,967
  • 1
  • 8
  • 19
  • 1
    The OP has a string, not a template literal. You've shown them how to do this with a template literal instead. – T.J. Crowder Sep 10 '21 at 16:56
  • updated with converting string to template literal – async await Sep 10 '21 at 17:05
  • This is not what the OP wants OP has strings with actual newlines, that he wants to be shown as C style escape sequences in the console – rep_movsd Sep 10 '21 at 17:07
  • Your update will result in `myString === myRawString` being `true` (assuming it doesn't fail because the string has `"` in it), so that doesn't help. ```const myString = "123\n456"; const myRawString = eval("String.raw`"+myString+"`"); console.log(myRawString === myString);``` (Shows `true`) There may well be a `String.raw` way to do this, but this isn't it, and `JSON.stringify` works well, so... :-) – T.J. Crowder Sep 10 '21 at 17:22