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

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);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)