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>  
  <html>  
    <body>  
      <h1>Hello, world!</h1>  
    </body>  
  </html>          
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];
  

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:

fs.ps.py.cs.js

Enjoy!


ArrowPrevious
NextArrow

Most Recent

23 June 2022
Is EdgeDB the Future?

EdgeDB solves some design flaws of relational and No-SQL databases. Read the differences between EdgeDB, MongoDB, and GraphQL and the best use cases for EdgeDB.

22 June 2022
Trello API Limits, 5 Best Practices to Avoid Rate Limiting

Third-party APIs like the Trello API can make life easier for developer. We'll discuss best practices to avoid rate limits in the Trello API.

22 June 2022
Using the Google Calendar API in React.js, An In-Depth Guide

We'll build a simple React app that uses Google Calendar API and that lists and adds events to your calendar. Let’s dive in.