Es6 multi-line pattern strings without newlines and allow indentation

Currently, more and more are using es6 for most jobs. One caveat is pattern strings.

I like to limit the number of line characters to 80. Therefore, if I need to concatenate a long string, it works fine because concatenation can be multiple lines, such as:

const insert = 'dog'; const str = 'a really long ' + insert + ' can be a great asset for ' + insert + ' when it is a ' + dog; 

However, trying to do this using template literals will simply give you a multi-line string with $ {insert}, placing the dog in the resulting string. Not ideal if you want to use template literals for things like collecting URLs, etc.

I have not yet found a good way to maintain a character limit limit and still use long template literals. Does anyone have any ideas?

Another question, marked as accepted, is only a partial answer. Below is another problem with templates that I forgot to include before.

The problem with using the new line characters is that it does not allow you to indent without inserting spaces in the ending line. i.e.

 const insert = 'dog'; const str = `a really long ${insert} can be a great asset for\ ${insert} when it is a ${insert}`; 

The resulting string is as follows:

 a really long dog can be a great asset for dog when it is a dog 

This is generally a small issue, but it would be interesting if there was a fix allowing multi-line indentation.

+5
source share
1 answer

Two answers to this problem, but only one can be considered optimal.

Inside template literals, javascript can be used inside expressions like ${} . Therefore, it is possible to have padding for multi-line patterns, such as the following. A caution is some valid character or js value that must be present in an expression, such as an empty string or variable.

 const templateLiteral = `abcdefgh${'' }ijklmnopqrst${'' }uvwxyz`; // "abcdefghijklmnopqrstuvwxyz" 

This method makes your code look like crap. Not recommended.

The second method was recommended by @SzybkiSasza and seems to be the best option. For some reason, the concatenation of template literals did not seem possible to me. I am derp.

 const templateLiteral = `abcdefgh` + `ijklmnopqrst` + `uvwxyz`; // "abcdefghijklmnopqrstuvwxyz" 
+8
source

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


All Articles