简体   繁体   中英

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM