Is it possible to have a comment inside a es6 Template-String?

lukash picture lukash · Oct 14, 2016 · Viewed 12.2k times · Source

Let's say we have a multiline es6 Template-String to describe e.g. some URL params for a request:

const fields = `
    id,
    message,
    created_time,
    permalink_url,
    type
`;

Is there any way to have comments inside that backtick Template-String? Like:

const fields = `
    // post id
    id,
    // post status/message
    message,
    // .....
    created_time,
    permalink_url,
    type
`;

Answer

Ori Drori picture Ori Drori · Oct 14, 2016

Option 1: Interpolation

We can create interpolation blocks that return an empty string, and embed the comments inside them.

const fields = `
  id,${ /* post id */'' }
  message,${ /* post status/message */'' }
  created_time,
  permalink_url,
  type
`;

console.log(fields);

Option 2: Tagged Templates

Using tagged templates we can clear the comments and reconstruct the strings. Here is a simple commented function that uses Array.map(), String.replace(), and a regex expression (which needs some work) to clear comments, and return the clean string:

const commented = (strings, ...values) => {
  const pattern = /\/{2}.+$/gm; // basic idea

  return strings
    .map((str, i) => 
      `${str}${values[i] !== undefined ? values[i] : ''}`)
    .join('')
    .replace(pattern, '');
};

const d = 10;
const fields = commented`
  ${d}
  id, // post ID
  ${d}
  message, // post/status message
  created_time, // ...
  permalink_uri,
  type
`;

console.log(fields);