Multi-line strings in JavaScript and Node.js

Hero Image

When writing Node.js or JavaScript applications, you sometimes need to embed multi-line strings in your code. It may be a snippet of HTML, a fragment of textual template, a piece of XML (remember XML?), or code in another programming language.

JavaScript has no built-in way of representing multi-line strings. If you need to embed a longer non-JavaScript text in your application the natural options are limited to concatenating several one-line JavaScript strings or using external files. Unless, of course, you use a little known trick:

   var html = (function () {/*  
  <!DOCTYPE html>  
      <h1>Hello, world!</h1>  

What happens here? An anonymous function is created with a function body consisting only of a multi-line comment. The comment itself is the very text you want to embed in your application. The function is then serialized to a string using toString(). Interestingly, the call preserves the function signature along with the function body and the comments within. Last, a regular expression is run over the serialized form of the function to extract the comment hidden inside. The end result assigned to the html variable contains the HTML content within the comment.

That pattern can be applied to a variety of types of multi-line text. For example, I am using the pattern liberally in the Edge.js project to embed (and later run) fragments of C#, F#, Python, or PowerShell code in a Node.js application:



Most Recent

24 January 2022
Run Node.js from Google Sheets

Import data from any API or data source to Google Sheets using Node.js, NPM, and Fusebit Connectors.

21 January 2022
Linear and Discord Slash Commands

Learn how to build an interactive Slash Command for a Discord bot that lets users create a new issue in Linear.

19 January 2022
Add Slash Commands to Your Discord Bot!

Slash Commands are an extremely powerful way to provide rich interactivity for members of your Discord server, all you have to do is type “/” and you're ready to use your favorite bot.