Reputation: 43
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
Upvotes: 4
Views: 1732
Reputation: 177685
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))
Upvotes: 3