Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print literal representation of a string in Node.js?

In my program there is a REPL loop that occassionaly need to print to the console a string representation of the given string variable. For example, suppose that we have have a string variable str defined somewhere in the program:

var str = "two\nlines";

I would like to have a print function (call it, for example, printRepr) that print to the console the string representation of str:

> printRepr(str);
"two\nlines"

I cannot find such a function in the documentation. Is there an easy way to get this behavior?

Note: I know that the Node.js REPL have this behavior, but i need a function that I would use in my program to print literal representation of any string. Of course, I cannot use console.log() because in that case I'd get this:

> console.log(str);
two
lines
like image 231
Jaroslav Modry Avatar asked Sep 03 '25 08:09

Jaroslav Modry


1 Answers

You can use util.inspect

const util = require('util');
const str = "two\nlines";
console.log(util.inspect(str));

Alternatively use String.raw or JSON.stringify (depending on your needs)

this will work in a browser too

console.log(String.raw`two\nlines`);

const str = `two\nlines`;
console.log(JSON.stringify(str))
like image 167
mplungjan Avatar answered Sep 04 '25 22:09

mplungjan