When using template literals I noticed a problem with table formats.
When doing something like this:
var hello = 'Hello',
bye = 'Goodbye';
console.log(`
${hello} World
${bye} World
`);
Because the {bye} part is four letters short of 'Goodbye' the string prints as:
Hello World
Goodbye World
This is made even more complex for interpolations of arrays, or objects.
I'm wondering if anyone has figured out a way to deal with this sort of problem. Where the spaced table formatting for a string can be kept during interpolation.
Suppose now a template tag uses strings, and arrays. The arrays are concatenated with spaces between words.
var hello = 'Hello',
bye = 'Goodbye',
phrase = ['I', 'like'];
console.log(someTag`
${hello} World
${bye} World
Some things I like:
${phrase} sunsets.
${['I', 'like']} candy.
`);
Just in case you can't tell the array square brackets, quotes, dollar, curly brace, and so on count towards the length of the string (visually) before interpolation. Spaces between words count towards string length after interpolation. The indents are effected by the loss of the extra characters, and addition of characters during the tag processing.
This question has an accepted answer, but I'd like to see more discussion. There can be more than one answer to this problem.
You can use tabs to compensate for the varying length of the words:
const hello = 'Hello';
const bye = 'Goodbye';
const str = `
${hello}\t World
${bye}\t World
`;
console.log(str);
document.getElementById('demo').innerText = str;
<pre id="demo"></pre>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With