Javascript: What is the cleanest way to build multi-line strings?

Created on 1 Aug 2018  路  4Comments  路  Source: airbnb/javascript

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;
}
question

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.

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zurfyx picture zurfyx  路  3Comments

koiralakiran1 picture koiralakiran1  路  3Comments

xgqfrms-GitHub picture xgqfrms-GitHub  路  3Comments

tpiros picture tpiros  路  3Comments

ar
mbifulco picture mbifulco  路  3Comments