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.

1
  • 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 stackoverflow.com/questions/805107/… Commented Mar 11, 2014 at 15:14

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

Comments

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 )

1 Comment

thanx for note about Storm
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>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.