Multiple lines of text or code with method ". html()"

Asked

Viewed 13,342 times

10

When using the jQuery method .html() to apply multiple lines of text or HTML code to an element, the same error:

Example in Jsfiddle

$(function(){
     $( '.qualquerClasse' ).html( ' conteúdo de 3 linhas de código: uma
         Duas
         Três' 
     );
});

Will generate the error:

Error: Syntaxerror: unterminated string literal

Question

How to apply multiple lines between quotes?

  • Ever tried to throw it all in one string only?

  • 3

    Hello Thiago, do not forget to format posted codes, on the edit screen you just need to select the code and click the button {} (or press the shortcut Ctrl+K)

  • If you need to do this over and over again, it might be worth checking out a template scheme like Handlebars.

  • Thank you all for your help. I’m getting familiar with the functions of stackoverflow ( and also jQuery kkk), Fabrício Matté speechless, responded immediately and with fantastic alternatives. I will check which works best and then comment more. Zuul thanks for editing and formatting .

  • @You were already an outsider in the best forms of web development in your time, 11 months ago, congratulations man! Template Engines was really what I needed, but at the time I didn’t even realize it; 2 months later I discovered and made a project with Node.js, express.js and jade.js got good, however, the best way I found, and what I currently use, is the Yeoman, learned the correct way to install and use watching the course of Jesus Christ, I no longer used template engine I put contents in arrays.

4 answers

18


Javascript does not allow literal line break characters inside strings.

There are several ways around the problem.

If you really want line breaks inside the string, use \n:

 $( '.qualquerClasse' ).html( 'conteúdo de 3 linhas de código: uma \n Duas \n Três' );

Note however that line-breaking characters within the HTML by default are not rendered (collapsed spaces) unless they are within an element whose computed value of the CSS property white-space be it pre/pre-wrap/pre-line. Otherwise (in most cases) it is necessary to use <br> to force a visible line break.

If you want to break the text into several lines to make it more readable, you can concatenate or use an array:

 $( '.qualquerClasse' ).html(
     ' conteúdo de 3 linhas de código: uma'
     + 'Duas'
     + 'Três'
 );
 //ou
 $( '.qualquerClasse' ).html([
     ' conteúdo de 3 linhas de código: uma',
     'Duas',
     'Três'
 ].join(''));

Of course you can add \n or <br> as needed in these strings.


There is also a non-standard way to "escape" line breaks by placing a \ just before the literal line break:

$( '.qualquerClasse' ).html( ' conteúdo de 3 linhas de código: uma\
     Duas\
     Três'
);

This syntax is not standard, but has very good support. However, some browsers keep the line break characters inside the string while others discard it, so this shape is a bit inconsistent. Another problem is that if you add any character after the \, even a space character, will generate a syntax error since the line break is no longer being escaped.

  • @Fabríciomatté hi! If you join strings template the response is modernized :)

4

So to complement: recommend the use of Coffeescript, a javascript processor (in the same way that SASS/LESS pre-process CSS).

Cofeescript offers a much more convenient and readable syntax. One of the many advantages is the possibility to define multi-line strings:

mobyDick = "Call me Ishmael. Some years ago --
  never mind how long precisely -- having little
  or no money in my purse, and nothing particular
  to interest me on shore, I thought I would sail
  about a little and see the watery part of the
  world..."

Or with """ to keep the formwork/indentation:

html = """
       <strong>
         cup of coffeescript
       </strong>
       """

2

A simple but not very recommended way to facilitate the error is to simply escape the line break with a bar \

 $( '.qualquerClasse' ).html( ' conteúdo de 3 linhas de código: uma\
     Duas\
     Três' 
 );

But the most recommended way, which avoids errors and does not hinder the minification of the code for production is shown by Fabrício Matté here.

  • Interesting answer, for pointing out why it is something not recommended.

1

ES6 (Ecmascript 2015) and Template literals (Template strings)

The "literals templates" are supported in:

  • Chrome 41+
  • Edge 12+
  • Firefox 34+
  • Safari 9+
  • Webview Android 41+
  • Node.js 4+

They support line breaking, which greatly facilitates "typing", example:

$(function(){
   $( '.qualquerClasse' ).html( ` conteúdo de 3 linhas de código: uma
       Duas
       Três` );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<pre class="qualquerClasse"></pre>

They support much more than line breaks, it is a "template" scheme, can pass variables like this ${var1} teste ${var2}, for example:

var x = 3, y = 100;

console.log(`O x é ${x}
e o y é ${y}`);

Would be equivalent to:

var x = 3, y = 100;

console.log('O x é ' + x + '\ne o y é ' + y);

In addition to variables it also supports operations, for example:

var x = 3, y = 100;

console.log(`${x}+${y} = ${x + y} e
5 * ${x} + 1 = ${5 * x + 1}.`);

Would be equivalent to:

var x = 3, y = 100;

console.log(x + '+' + y + ' = ' + (x + y) + ' e\n5 * ' + x + ' + 1 = ' + (5 * x + 1) + '.');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.