Menu

Working with multiline strings in JavaScript

Working with multiline strings in JavaScript

Today I am going to talk about a seemingly boring topic, strings in JavaScript. But stay with me, as we'll be going into some low-level concepts that are important to know to have more control over your code. We'll be talking about strings that span multiple lines to be exact. Because they are surprisingly more involved than you might realize in JavaScript.

Multiline strings are not anything brand new that will blow your mind into oblivion. Other languages have them, such as C#, Java and JavaScript supports them now too thanks to ES6 template literals. Let's start off with a quick definition of what they are and why they can be so useful.

Multiline strings are just that. They are strings that can span multiple lines when declaring them and initializing them into variables. Compared to the traditional model, in which all JavaScript strings must be enclosed on a single line less you end up with a syntax error.

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 = '
<div>
    <p>Hey there</p>
    <p>How goes it</p>
</div>';

And I won't get into it in this post as to whether injecting HTML using JavaScript variables is a best practice or not. Let's assume that your code just so happens to make use of it, and it makes sense for the project.

Due to a bug in JavaScript however, clever programmers were able to overcome that obstacle by using the '\' escape character just before adding a newline.

let message = 'this is multiline \
message \
with multiple lines';

While this works just fine even today, JavaScript now has its own official and standardized way of accomplishing multiline strings. And that would be using template literals in ES6, which fixes that issue once and for all. Which is great, as we should steer clear of bug-based fixes for future-proofing software.

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

There is no extra work that is required here to include multilines. However, any whitespace in the above string would still be treated by JavaScript as such and so tabbing data to align it for readability will still create excess whitespace characters in your code. Let's take a look at that further below.

Excess whitespace

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.

The previous code would render like the following by most JavaScript engines if you were to output it.

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.

As you can see, somewhat complex and involved but a few key points to remember going forward when working with strings in JavaScript. Hopefully you enjoyed this low-level look into JavaScript in a new series that I will be dubbing, "Under the Hood". Sign up for the newsletter to stay up to date on future deep dives. And Comment below if you have a solid way to accomplish multiline string concatenation, with auto-indentation, that doesn't effect the overall length of the string.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet
Ad Unit

Current Poll

Total Votes:
Q:
Submit

Add a comment