As the title mentions, what do you all think is the cleanest way to build an multi-line string.
For example, what if I want to define a function that builds a multiline string that looks like the following:
Your groups:
Group1
Group2
Here are examples of ways I was considering accomplishing this:
(The function in the example is necessary to show how strange the indentation in code will look for template strings)
function doSomething() {
const text = 'Your groups:'
+ '\nGroup1'
+ '\nGroup2';
return text;
}
vs
// Subsequent lines in the string have no indent in code because we don't want indents in the string
function doSomething() {
const text = `Your groups:
Group1
Group2`;
return text;
}
Another example is putting the strings into an array and then joining:
function doSomething() {
const text = ['Your groups', 'Group1', 'Group2'].join('\n');
return text;
}
Joining an array is a legacy hack from when that was faster in ancient browsers; in anything even remotely modern, there's not a huge benefit.
A template literal is the proper way to build a multiline string. There's tagged template literal libs like https://www.npmjs.com/package/dedent and https://www.npmjs.com/package/deline tho, that can make this cleaner.
Use ES6 template literals where strings are started and ended with ` symbol.
`hello
world`
is equivalent to ....
"hello \nworld"
Closing; this seems answered.
Most helpful comment
Joining an array is a legacy hack from when that was faster in ancient browsers; in anything even remotely modern, there's not a huge benefit.
A template literal is the proper way to build a multiline string. There's tagged template literal libs like https://www.npmjs.com/package/dedent and https://www.npmjs.com/package/deline tho, that can make this cleaner.