187

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.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
700 Software
  • 85,281
  • 83
  • 234
  • 341
  • 1
    Why on earth would you need to insert hard line returns? Nothing in the DOM supports that (excepting "pre"), and all the other common return types don't care. – jcolebrand Jun 02 '11 at 21:41
  • So I don't end up with tabs on the left without returns on the right. I like to have either both or none. Right now I am using `print( '
    ')` to print my HTML. It has neither tabs nor returns which is "neat", but it would be easier to use a Perl `<
    – 700 Software Jun 03 '11 at 00:22
  • 9
    @jcolebrand: Node.JS is not primarily concerned with DOM manipulation. It's a full application development environment. See http://nodejs.org – Roy Tinker Oct 11 '11 at 02:28
  • @RoyTinker yes, but he called out browsers at the time, and on top of that he called out non-`\n` implementations, so ... that's pretty well only browsers. – jcolebrand Oct 11 '11 at 03:08
  • @GeorgeBailey If you still use stack overflow, could you fix the correct answer here? – mikemaccana May 27 '16 at 21:55
  • Hi @GeorgeBailey! Thanks for coming back. Yes, I'm asking to change the accepted answer to Vijey's, to help other people who want to know if JS has a Multiline string feature. – mikemaccana May 29 '16 at 13:59
  • @GeorgeBailey Though the community disagrees, you're the asker so it's your prerogative. I've edited the current answer to make it clearer. – mikemaccana May 30 '16 at 16:35

9 Answers9

242

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.

Rob Raisch
  • 17,040
  • 4
  • 48
  • 58
  • I think I will end up using http://stackoverflow.com/questions/805107/multiline-strings-in-javascript/5571069#5571069. I may expand on it so I can use variables. It will be creative for sure! But since this is Node.JS, I don't have to worry about browser compatibility, and in my case, not even version compatibility. – 700 Software Jun 04 '11 at 21:53
  • 6
    *"Javascript does not support multi-line strings..."* It does as of ES5, and it's in V8 (Google's JavaScript engine), so presumably in NodeJS (which uses V8). See *LineContinuation* in [Section 7.8.4]*(http://es5.github.com/#x7.8.4). Tools support may be sketchy for a while. – T.J. Crowder Mar 18 '12 at 11:21
  • It is in io.js but not Node.JS yet - I added an answer with a couple more links – Simon D Aug 03 '15 at 14:38
  • 1
    Node 4.0+ now supports multiline strings intrinsically. – Rob Raisch Jan 03 '16 at 02:59
  • Is string interpolation with back ticks slower than any other of the non-"language construct" solutions? I.e. `join` and `+` etc.? – lol Jan 09 '22 at 07:41
  • For 100mill iterations using three short strings separated by spaces, using joins is the slowest (9.3sec), using three String.concats is next (6.5sec), then using one String.concat for all values (5.8sec), and finally, using plus concatenation vs. string templates are neck-and-neck (4.5sec) with string templates consuming 0.006sec more than pluses, or 0.00000000006sec per template. – Rob Raisch Jan 11 '22 at 20:31
57

Multiline strings are a current part of JavaScript (since ES6) and are supported in node.js v4.0.0 and newer.

var text = `Lorem ipsum dolor 
sit amet, consectetur 
adipisicing 
elit.  `;

console.log(text);
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Vijey
  • 6,536
  • 7
  • 43
  • 50
  • 3
    This answer should be voted to the top immediately! See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings for details on template strings. – user3413723 Dec 11 '15 at 10:48
  • 2
    Might want to note that you can easily add variables by adding ${variablehere} syntax inside the template (the ` ` ticks) – Joseph Astrahan Sep 24 '18 at 05:22
45

What exactly are you looking for when you mean multiline strings.

Are you looking for something like:

var str = "Some \
    String \
    Here";

Which would print as "Some String Here"?

If so, keep in mind that the above is valid Javascript, but this isn't:

var str = "Some \ 
    String \
    Here";

What's the difference? A space after the \. Have fun debugging that.

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
Robert
  • 21,110
  • 9
  • 55
  • 65
  • well bollocks that. It won't let me show the space after the \ without putting a character there. – jcolebrand Jun 02 '11 at 21:40
  • 1
    @jcolebrand: Yes, quite fun isn't it :P – Robert Jun 02 '11 at 22:02
  • ) http://meta.stackexchange.com/questions/93581/how-can-we-display-additional-spaces-using-markdown – jcolebrand Jun 02 '11 at 22:13
  • 1
    This is a dirty hack. Please no! – Raynos Jun 02 '11 at 22:59
  • @jcolebrand: I didn't mean just stackoverflow, but in IDE's and debuggers. @Raynos: "Hacks" are just making things work that weren't originally thought of. Some are bad hacks, but that wasn't part of the question :P – Robert Jun 03 '11 at 02:08
  • @Raynos I agree, but it works. It's nice for HTML and SQL strings in your JavaScript code. I'll admit... it's a hack, but it helps make your HTML or SQL string more readable. – BMiner Jul 12 '11 at 21:04
  • @BMiner I look at it differently. If you have multiline HTML strings your doing it wrong. Use the DOM. If you have SQL strings then seperations of concerns maybe? Why the heck does your js have inline SQL? – Raynos Jul 13 '11 at 00:24
  • @Raynos I do quite a bit a server-side JavaScript development, not just client-side, which is why there are sometimes long HTML or SQL strings in my code. Check out Node.js! – BMiner Jul 13 '11 at 18:13
  • @BMiner ... I do server-side development as well, I use a proper templating engine to avoid inline HTML. There's no excuse for inline HTML. In-line SQL feels dirty aswell, you need a better solution probably noSQL. To be honest its worse on the server. if your a node.js developer you should know better then to use hacks like this. – Raynos Jul 14 '11 at 02:27
  • @Raynos Hmm... I suppose you're right, but there are worse hacks than this. I suppose string concatenation is OK. – BMiner Jul 15 '11 at 16:32
  • @BMiner seriously though, please re-factor this hack away when you have time. It's code-debt. – Raynos Jul 16 '11 at 01:44
  • 1
    Thanks @Robert, the space after '\' insight saved me some time! – gpestana Oct 13 '16 at 07:45
11

In addition to accepted answer:

`this is a 
single string`

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

If you want to use string interpolation but without a new line, just add backslash as in normal string:

`this is a \
single string`

=> 'this is a single string'.

Bear in mind manual whitespace is necessary though:

`this is a\
single string`

=> 'this is asingle string'

suvtfopw
  • 928
  • 10
  • 18
9

As an aside to what folks have been posting here, I've heard that concatenation can be much faster than join in modern javascript vms. Meaning:

var a = 
[ "hey man, this is on a line",
  "and this is on another",
  "and this is on a third"
].join('\n');

Will be slower than:

var a = "hey man, this is on a line\n" + 
        "and this is on another\n" +
        "and this is on a third";    

In certain cases. http://jsperf.com/string-concat-versus-array-join/3

As another aside, I find this one of the more appealing features in Coffeescript. Yes, yes, I know, haters gonna hate.

html = '''
       <strong>
         cup of coffeescript
       </strong>
       '''

Its especially nice for html snippets. I'm not saying its a reason to use it, but I do wish it would land in ecma land :-(.

Josh

Josh
  • 12,602
  • 2
  • 41
  • 47
  • 1
    The only thing wrong with CoffeeScript for me, is the same thing wrong with Groovy last I checked. When a file is converted from `.coffee` to `.js`, the line numbers are jumbled. I have not tried CoffeeScript, but when I tried Groovy, I found it quite difficult to debug without getting the generated `.java` files. – 700 Software Jun 04 '11 at 21:56
  • I've written some reasonably large projects in coffee. You do end up having to look at the compiled code. It is, however, easy to read. imo there is still an unacceptable stigma with coffeescript in the node community, though several large projects are written in it (zombie.js, pow, riak-js). I'm currently porting some of my smaller OSS over, because people say 'oh, coffee, yuck' and immediately move on, despite the fact that you don't have to use coffee to use the library. – Josh Jun 05 '11 at 18:39
  • I'm a hater of Coffeescript. :P But, I'm definitely a fan of the ''' string block! Or... PHP heredoc syntax. – BMiner Jul 13 '11 at 18:25
  • The array pattern (using join('\n')) will be slower than plain-old string concatenation in most cases. – BMiner Jul 17 '11 at 12:40
  • 1
    Except for IE7 and below, this is true. And you'll note, I said that and linked to jsperf. – Josh Jul 19 '11 at 16:44
  • As the question is regarding node.js it's a decent answer. – Tracker1 Oct 09 '12 at 22:20
8

Take a look at the mstring module for node.js.

This is a simple little module that lets you have multi-line strings in JavaScript.

Just do this:

var M = require('mstring')

var mystring = M(function(){/*** Ontario Mining and Forestry Group ***/})

to get

mystring === "Ontario\nMining and\nForestry\nGroup"

And that's pretty much it.

How It Works
In Node.js, you can call the .toString method of a function, and it will give you the source code of the function definition, including any comments. A regular expression grabs the content of the comment.

Yes, it's a hack. Inspired by a throwaway comment from Dominic Tarr.


note: The module (as of 2012/13/11) doesn't allow whitespace before the closing ***/, so you'll need to hack it in yourself.

David Murdoch
  • 87,823
  • 39
  • 148
  • 191
  • 1
    Or use your branch of mstring which contains the whitespace fix. Thanks! https://github.com/davidmurdoch/mstring – Druska Jul 23 '13 at 21:12
4

Take a look at CoffeeScript: http://coffeescript.org

It supports multi-line strings, interpolation, array comprehensions and lots of other nice stuff.

Ricardo Tomasi
  • 34,573
  • 2
  • 55
  • 66
1

If you use io.js, it has support for multi-line strings as they are in ECMAScript 6.

var a =
`this is
a multi-line
string`;

See "New String Methods" at http://davidwalsh.name/es6-io for details and "template strings" at http://kangax.github.io/compat-table/es6/ for tracking compatibility.

Simon D
  • 4,150
  • 5
  • 39
  • 47
0

Vanilla Javascipt does not support multi-line strings. Language pre-processors are turning out to be feasable these days.

CoffeeScript, the most popular of these has this feature, but it's not minimal, it's a new language. Google's traceur compiler adds new features to the language as a superset, but I don't think multi-line strings are one of the added features.

I'm looking to make a minimal superset of javascript that supports multiline strings and a couple other features. I started this little language a while back before writing the initial compiler for coffeescript. I plan to finish it this summer.

If pre-compilers aren't an option, there is also the script tag hack where you store your multi-line data in a script tag in the html, but give it a custom type so that it doesn't get evaled. Then later using javascript, you can extract the contents of the script tag.

Also, if you put a \ at the end of any line in source code, it will cause the the newline to be ignored as if it wasn't there. If you want the newline, then you have to end the line with "\n\".

Tim Caswell
  • 439
  • 3
  • 3
  • answer is out of date, see `` syntax added into newer versions of node, in other comments – aqm Sep 29 '21 at 10:55