1

I have to assign an HTML string through the following Javascript code. However, this seems to be possible only if I put all the HTML on one line.

This works:

var assignedhtml = "<div> <p>It's the most beautiful thing I've seen in my life </p> <p> It's watermalone </p> </div>"

This does not work:

var assignedhtml = "<div>
                    <p>It's the most beautiful thing I've seen in my life </p>
                    <p> It's watermalone </p>
                    </div>"

The issue is that I have too many lines my html code. In the past, I have individually removed all the \n (newline) characters. Is there a simpler way to achieve the variable assignment I intend without having to individually go through the lines and delete the newline characters?

i.e., I want to keep the html code on the right as is in the second case above, but remove the newlines before assigning it to the variable.

couchand
  • 2,639
  • 1
  • 21
  • 27
Venomoustoad
  • 1,203
  • 1
  • 14
  • 38
  • 1
    actually.. no. javascript string must be normally in one line. You can however use an escape charatcer `\` to split it into more lines, but still this does not help you, as you also have to do this manually http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript – Asped Mar 11 '14 at 15:14

3 Answers3

1

There's no equivalent to, for instance, PHP's heredoc but you can add backslashes to escape the hard returns:

var assignedhtml = "<div>\
  <p>It's the most beautiful thing I've seen in my life </p>\
  <p> It's watermalone </p>\
  </div>";

Here's a working example: http://jsfiddle.net/9W6BS/

Cody Brumfield
  • 487
  • 4
  • 10
0

You can do it like this:

var assignedhtml = '<div>' +
'<p>It\'s the most beautiful thing I've seen in my life</p>' +
'<p>It\'s watermelon</p>' +
'</div>';
Serlite
  • 12,130
  • 5
  • 38
  • 49
vdwijngaert
  • 1,515
  • 11
  • 24
0

One more variant - use '\' symbol at the and of line

Valid code example

    var assignedhtml = "<div>\
            <p>It's the most beautiful thing I've seen in my life </p>\
            <p> It's watermalone </p>\
            </div>"

Also want to note, that some tools ( like webStorm or PhpStorm) allow to edit such injections in normal mode ( Alt + enter - edit HTML Fragment )

Vasiliy vvscode Vanchuk
  • 7,007
  • 2
  • 21
  • 44