Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

javascript - es6 multiline template strings with no new lines and allow indents

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

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

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...