How do I do a multi-line string in node.js?

Bryan Field picture Bryan Field · Jun 2, 2011 · Viewed 119.8k times · Source

With the rise of node.js, multi-line strings are becoming more necessary in JavaScript.

  1. Is there a special way to do this in Node.JS, even if it does not work in browsers?
  2. Are there any plans or at least a feature request to do this that I can support?

I already know that you can use \n\ at the end of every line, that is not what I want.

Answer

Rob Raisch picture Rob Raisch · Jun 2, 2011

node v4 and current versions of node

As of ES6 (and so versions of Node greater than v4), a new "template literal" intrinsic type was added to Javascript (denoted by back-ticks "`") which can also be used to construct multi-line strings, as in:

`this is a 
single string`

which evaluates to: 'this is a\nsingle string'.

Note that the newline at the end of the first line is included in the resulting string.

Template literals were added to allow programmers to construct strings where values or code could be directly injected into a string literal without having to use util.format or other templaters, as in:

let num=10;

console.log(`the result of ${num} plus ${num} is ${num + num}.`);

which will print "the result of 10 plus 10 is 20." to the console.

Older versions of node

Older version of node can use a "line continuation" character allowing you to write multi-line strings such as:

'this is a \
single string'

which evaluates to: 'this is a single string'.

Note that the newline at the end of the first line is not included in the resulting string.