Can I leave a comment inside the es6 template?

Say we have an es6 multi-line template for description, for example. Some URL parameters for the request:

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

Is there a way to have comments inside this Template-String? How:

 const fields = ` // post id id, // post status/message message, // ..... created_time, permalink_url, type `; 
+15
source share
4 answers

No.

This syntax is valid, but just returns a string containing \n// post id\nid , instead of deleting comments and creating a line without them.

If you look at the Β§11.8.6 specification , you will see that the only marker recognized between the countdown delimiters is TemplateCharacters, which accepts escape sequences, line breaks, and regular characters. In Β§A.1 , SourceCharacter is defined as any Unicode point (except those excluded in 11.8.6).

+7
source

Option 1: Interpolation

We can create interpolation blocks that return an empty string and embed comments in them.

 const fields = ' id, ${ /* post id */'' } message, ${ /* post status/message */'' } created_time, permalink_url, type '; console.log(fields); 

Option 2: tagged templates

Using tag templates , we can clear comments and restore lines. Here is a simple commented function that uses Array.map() , String.replace() and a regex expression (which takes some work) to clear comments and return a clean line:

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

+51
source

I know that this is an old answer, but, seeing the answers above, I feel obligated to answer a clean question and then answer the question of the spirit of the person asking.

Can you use comments in template literal lines?

Yes. Yes you can. But it is not beautiful.

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

Note that you must put '' (empty string) in curly braces ${ } so that there is an expression to insert in Javascript. Failure to do so will result in a runtime error. Quotation marks may be outside the comment.

I am not a big fan of this. This is pretty ugly and makes commenting cumbersome, not to mention switching comments becomes difficult in most IDEs.

Personally, I use template strings wherever possible, as they are much more efficient than regular strings, and they capture literally all the text you want, mostly without escaping. You can even make function calls there!

The line in the example above will be a little strange and potentially useless for what you are looking for, however, there will be an initial line break, an extra space between the comma and the comment, and an additional ending Line break. Removing this unnecessary space can be a small hit on performance. You can use regular expressions for this, for speed and efficiency, though ... more on that below ...

.

Now, to answer the question:

How to write a list line separated by commas with comments for each line?

 const fields = [ "id", // post ID "message", // post/status message "created_time", //... "permalink_url", "type" ].join(",\n"); 

Joining an array is one way ... (as suggested by @ jared-smith)

However, in this case, you create an array, and then immediately discard the organized data when you only assign the return value of the join() function. In addition, you create a memory pointer for each row in the array that will not collect garbage until the end of the scope. In this case, it may be more useful to capture the array, joining on the fly, as required by the use, or use a template literal and comment on your implementation in different ways, for example, the ghostDoc style.

It seems that you use template literals only to satisfy the desire not to have quotes in each line, minimizing the cognitive dissonance between the 'string' query parameters when they look in the url and code. You should know that this keeps line breaks, and I doubt you want it. Consider instead:

 /**************** * Fields: * id : post ID * message : post/status message * created_time : some other comment... */ const fields = ' id, message, created_time, permalink_uri, type '.replace(/\s/g,''); 

Uses a regular expression to filter the entire space, keeping the list readable and rearranged. Everything the regular expression literal does is capture a space, and then the replace method replaces the captured text with '' ( g at the end simply tells the regular expression not to stop at the first match found, in this case, the first newline.)

or, worst of all, you can just put the comments directly in the template literal and then delete them with a regex:

 const fields = ' id, // post ID message, // post/status message created_time, // ... permalink_uri, type '.replace(/\s+\/\/.*\*\/\n/g,'').replace(/\s/g,''); 

This first regular expression will find and replace with an empty string ( '' ) all instances: one or more whitespace characters that precede the double slash (each slash is escaped with a backslash), followed by whitespace and a newline if you want use the comments /* multiline */ , this regex is getting a little more complicated, you need to add another .replace() at the end:

 .replace(/\/\*.*\*\//g,'') 

This regular expression can appear only after you delete new lines \n , otherwise the regular expression will not match the comment, which is now not multi-line. It will look something like this:

 const fields = ' id, // post ID message, /* post/ status message */ created_time, // ... permalink_uri, type '.replace(/\s+\/\/.*\n/g,'').replace(/\s/g,'').replace(/\/\*.*\*\//g,''); 

All of the above will result in this line:

"id,message,created_time,permalink_uri,type"

There is probably a way to do this with just one regex, but in fact it goes beyond that. And besides, I would advise you to fall in love with regular expressions, playing with them yourself!

I will try to pick up https://jsperf.com/ later. I'm very curious now!

+8
source

Just don't use pattern strings:

 const fields = [ 'id', // comment blah blah 'message', 'created_time', 'permalink_url', 'type' ].join(','); 

You pay the cost of calling the array and method on initialization (if the JIT is not smart enough to fully optimize it.

As ssube pointed out, the resulting line will not save line breaks or spaces. It depends on how important this is, you can manually add '' and '\ n' if necessary, or decide that you really don't need inline comments that are bad.

UPDATE

Note that storing program data in strings is usually considered a bad idea : instead, save it as named vars or object properties. Since your comment reflects your simple conversion of a bunch of things to a url query string:

 const makeQueryString = (url, data) => { return url + '?' + Object.keys(data) .map(k => `${k}=${encodeURIComponent(data[k))}) .join('&'); }; let qs = makeQueryString(url, { id: 3, message: 'blah blah', // etc. }); 

Now you have things that are easier to change, understand, reuse and more transparent for code analysis tools (for example, in your IDE of choice).

+2
source

Source: https://habr.com/ru/post/1258217/


All Articles