8

The only way I know how to print a huge string without using += is to use \ backslashes. ugly!

<div id="foo"></div>
<script type="text/javascript">
var longString = '<div id="lol">\
        <div id="otherstuff">\
            test content. maybe some code\
        </div>\
    </div>';

document.getElementById('foo').innerHTML = longString;
</script>

is there any way to do this where the longString is untainted? php has $foo = ''' long multiline string '''; I want this in javascript!

Anyone know of a better method for printing long, multi-line strings in javascript?

tester
  • 22,441
  • 25
  • 88
  • 128
  • 2
    possible duplicate of [Javascript HERE-doc or other large-quoting mechanism?](http://stackoverflow.com/questions/2953682/javascript-here-doc-or-other-large-quoting-mechanism) – Wolph Nov 11 '10 at 02:29
  • possible duplicate of https://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript – mathheadinclouds Nov 08 '19 at 18:14

5 Answers5

5

In general, the answer is: not in the language syntax. Though as Ken pointed out in his answer there are many work-arounds (my personal method is to load a file via AJAX). In your specific case though, I'd prefer creating a HTML constructor function so you can then define the HTML structure using javascript object literals. Something like:

var longString = makeHTML([{
  div : {
    id : "lol",
    children : [{
      div : {
        id : "otherstuff",
        children : [{
            text : "test content. maybe some code"
        }]
    }]
 }]

which I find to be much easier to handle. Plus, you this would allow you to use real function literals when you need it to avoid string quoting hell:

makeHTML([{
  span : {
    onclick : function (event) {/* do something */}
  }
}]);

note: the implementation of makeHTML is left as exercise for the reader


Additional answer:

Found some old code after a quick scan through my hard disk. It's a bit different from what I suggested above so I thought I'd share it to illustrate one of the many ways you can write functions like this. Javascript is a very flexible language and there is not much that forces you to write code one way or another. Choose the API you feel most natural and comfortable and write code to implement it.

Here's the code:

function makeElement (tag, spec, children) {
    var el = document.createElement(tag);
    for (var n in spec) {
        if (n == 'style') {
            setStyle(el,spec[n]);
        }
        else {
            el[n] = spec[n];
        }
    }
    if (children && children.length) {
        for (var i=0; i<children.length; i++) {
            el.appendChild(children[i]);
        }
    }
    return el;
}

/* implementation of setStyle is
 * left as exercise for the reader
 */

Using it would be something like:

document.getElementById('foo').appendChild(
  makeElement(div,{id:"lol"},[
    makeElement(div,{id:"otherstuff"},[
      makeText("test content. maybe some code")
    ])
  ])
);

/* implementation of makeText is
 * left as exercise for the reader
 */
slebetman
  • 109,858
  • 19
  • 140
  • 171
4

One technique if you have a big block is a <script> tag with an invalid type. It will be ignored by browsers.

<script type="text/x-my-stuff" id="longString">
    <div id="lol">
        <div id="otherstuff">
            test content. maybe some code
        </div>
    </div>
</script>
<script type="text/javascript">
    var longString = document.getElementById("longString").text;
    document.getElementById('foo').innerHTML = longString;
</script>
Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • instead of an invalid type, you can also use the language attribute, setting language='text', and omitting the type. See Pointy's answer here: https://stackoverflow.com/questions/2953682/javascript-here-doc-or-other-large-quoting-mechanism Effect seems to be exactly the same, but to calm down those poor creatures how shudder at everything invalid and hacky... – mathheadinclouds Nov 08 '19 at 18:03
  • The `language` attribute has long been deprecated in favour of the `type` attribute which was actually properly specified. I find it reasonable to therefore consider that technique strictly inferior to this one, given also their compatibility. But really, this whole question is long out of date; backtick-delimited strings would be the right approach nowadays. – Chris Morgan Nov 20 '19 at 00:23
  • backticks don't work in IE. you're right about the deprecation. I use your method to this day, with type='invalid'. – mathheadinclouds Nov 20 '19 at 00:30
1

A few somewhat unattractive options are discussed in the answers to this question.

Community
  • 1
  • 1
Ken Redler
  • 23,863
  • 8
  • 57
  • 69
1

You really could minimize this ugliness by creating your <div id="lol"> as HTML, and set its content with .innerHTML = "test content. maybe some code"

I don't like creating HTML in Javascript because of this exact issue, and instead use "template" elements which i simply clone then manipulate.

var lol = document.getElementById("template_lol").clone();
lol.firstChild.innerHTML = "code and stuff";
foo.appendChild(lol);

And this is the HTML:

<body>
<div>normal stuff</div>

<div style="display:none" id="templateBucket">
  <div id="template_lol"><div class="otherstuff"></div></div>
</div>
</body>
Jeff Meatball Yang
  • 37,839
  • 27
  • 91
  • 125
1

This works too :

var longString = 
  '<div id="lol">' +
    '<div id="otherstuff">' +
      'test content. maybe some code' +
    '</div>' +
  '</div>';
Alain Beauvois
  • 5,896
  • 3
  • 44
  • 26