Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Been using es6 more and more for most work these days. One caveat is template strings.

I like to limit my line character count to 80. So if I need to concatenate a long string, it works fine because concatenation can be multiple lines like this:

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 that with template literals would just give you a multi-line string with ${insert} placing dog in the resulting string. Not ideal when you want to use template literals for things like url assembly, etc.

I haven't yet found a good way to maintain my line character limit and still use long template literals. Anyone have some ideas?

The other question that is marked as an accepted is only a partial answer. Below is another problem with template literals that I forgot to include before.

The problem with using new line characters is that it doesn't allow for indentation without inserting spaces into the final string. 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 looks like this:

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

Overall this is a minor issue but would be interesting if there was a fix to allow multiline indenting.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
393 views
Welcome To Ask or Share your Answers For Others

1 Answer

Two answers for this problem, but only one may be considered optimal.

Inside template literals, javascript can be used inside of expressions like ${}. Its therefore possible to have indented multiline template literals such as the following. The caveat is some valid js character or value must be present in the 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 available. For some reason concatenating template literals didn't occur to me as possible. I'm derp.

const templateLiteral = `abcdefgh` +
  `ijklmnopqrst` +
  `uvwxyz`;

// "abcdefghijklmnopqrstuvwxyz"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...