let message = 'this is a normal message';
If you were to split that string up into multiple lines, you would get an error.
let message = 'this is a
normal message'; // not allowed
Why would you want to have multiline strings you ask? Excellent question. The main answer that you'll encounter most often is that it will aid in readability. Say for example that you wanted to render the following line of HTML onto your page.
let html = '<div><p>Hey there</p><p>How goes it</p></div>';
The browser will render HTML the same regardless of whitespace in or around the string. HTML uses CSS for styling, and not character encoded whitespace. But for your sake, it would be nice to make the content more readable. Compare that to the following:
let html = '
<p>How goes it</p>
let message = 'this is multiline \
with multiple lines';
The only challenge here is that you'll need to use the hard to locate 'tick' key on your keyboard (top left most key's secondary value). The string literal syntax allows for any whitespace formatting without breaking your code.
let message = `an es6 string
literal broken down
into multiple lines`; // works great
While string literals are the most natural way of including multiline text in your code, it still falls slightly short in the 'truly being multiline' respect. And that is mainly because most code editors will auto indent your code for you for readability. Take the following variable declaration for example, in which VSCode indented each new line for me.
That is the intended outcome of course. We want all whitespace and newlines preserved here for ease of use and readability as mentioned. But the unnoticed effect is that the length of the string will also reflect this invisible space!
Here is the calculated length of that string in particular.
And the above would be the same whether using the string template format or the '\' fix.
If you are looking for a way to allow for multiline usage while still only keeping the text flush to the left, then you could consider removing 'tab' elements from your string or use a regular expression in order to remove all but the first whitespace character on each line during some kind of pre-processor phase.
Did you find this article helpful?
Walter G. is a software engineer, startup co-founder, former CTO of several tech companies and currently teaches programming for a coding bootcamp. He has been blogging for the past 5 years and is an avid BMX rider, bio-hacker
and performance enthusiast.