Template Literals Juxtaposition and String.join

Proposal url: proposal-template-literals-juxtaposition/README.md at main 路 futurist/proposal-template-literals-juxtaposition 路 GitHub

Try to proposal below template literals ability:

var template = `This is `
    `in a `

template === 'This is in a line.';

Thus be a way to enable the RegExp Free-Spacing Mode to JS world, like passing the joined template literal to String.raw.

1 Like

I think that is not possible, because this is currently valid code:

var template = String.raw`This is `
    `in a `

The fact that it throws an error at runtime is kinda irrelevant. You can have tag functions that return functions, and those can then apply to subsequent chunks:

function foo(strings) {
  console.log('foo', strings);
  strings.forEach(s => foo.totalLength += s.length);
  return foo;
foo.totalLength = 0;

var template = foo`This is `
    `in a `

console.log(typeof template);

This makes 3 calls to foo. You would need to change that to just one, with the chunks concatenated in advance.

1 Like

See https://github.com/tc39/proposal-string-dedent


Yes in the proposal I've pointed the problem and marked "discussed later".

This cannot enable the RegExp String.raw with comments ability?

Ah, true. You can stick a comment anywhere in a template literal you like with ${''/* comment */} tho.

What about the alternative of allowing empty interpolations (${}${/* ... */}) and simply ignoring them for the purpose of template literal parsing? This would also carry the benefit of allowing template-level comments within arbitrary tagged template literals without needing the tag itself to specially handle empty strings or anything like that.

I would find treating ${} as if nothing was there a little weird.

> tag = parts => console.log(parts)
> tag`a${2}b${}c`
[ 'a', 'b', 'c' ] // expected result
[ 'a', 'bc' ] // actual result

There are some other options to solve the specific example that was originally brought up, for example, you can just concatenate raw strings together as follows:

const r = String.raw
const template = (
  r`This is ` +
  r`in a ` + // A comment

template === 'This is in a line.';

Some more complicated template tags will already support comments inside the template string. e.g. a css tag should support CSS-style comments.

As for wanting whitespace/comment support in regular expressions, check out this thread that's seeking to add a verbose flag for regular expressions, to provide this kind of support.

None of these things help with the general problem, but can help out in a handful of specific situations.