FORSMILE
JA
JavaScript2021/08/31

How to Write Multi-line Strings in JavaScript Variables

When using jQuery's append, you might occasionally need to assign a rather long HTML string to a variable.

Back to Blog

When using jQuery's append, you might occasionally need to assign a rather long HTML string to a variable.

This article explains how to write strings that include newlines when assigning them to variables in JavaScript.

USING BACKTICKS (`)

This is a straightforward method of simply enclosing a string that includes newlines within backticks (`).

javascript
var userInfo = `
    <div class="user">
        <div class="close">✕</div>
        <div class="message">Sample JavaScript</div>
        <a href="#" class="btn-basic">OK</a>
    </div>
`;
javascript
var btnClass = "btn-basic";
var userInfo = `
    <div class="user">
        <div class="close">✕</div>
        <div class="message">Sample JavaScript</div>
        <a href="#" class="` + btnClass + `">OK</a>
    </div>
`;

Backticks (`) can usually be typed by pressing `SHIFT + @`. It's quite simple, as you just enclose the text within them!

USING BACKSLASHES (\) FOR NEWLINES

javascript
var userInfo = '\
    <div class="user">\
        <div class="close">✕</div>\
        <div class="message">Sample JavaScript</div>\
        <a href="#" class="btn-basic">OK</a>\
    </div>\
';

As shown above, you simply write a backslash (\) at each point where a newline occurs. However, this method involves more effort compared to using backticks (`).

This can make the code clearer when you need to append a long HTML string using jQuery.

RECOMMENDED JAVASCRIPT BOOKS

JavaScript has a wealth of information available online, and Google searches are highly convenient, so you might not feel the need to read books.

However, beginners might find that reading a simple introductory book can deepen their understanding. While there are good reverse-lookup reference books, Google searches are often more convenient for copying and pasting code snippets, making dedicated reference books less essential.

Eye-opening! JavaScript — Understanding the Essence of JavaScript from Language Specifications

Highly recommended! You'll learn JavaScript concepts that don't always surface in a quick Google search. Finishing this book made me feel my coding skills had advanced significantly.

RECOMMENDED JQUERY BOOKS

Many jQuery books tend to be outdated. However, jQuery itself continues to evolve.

📦
Amazon で関連書籍・ツールを検索
JavaScript programming book
Amazonで探す →(アソシエイトリンク)