Storing HTML or XML code in javascript variables

前端 未结 4 1583
悲&欢浪女
悲&欢浪女 2021-01-21 14:16

I\'d like to store a some HTML/XML markups in a javascript variable. The problem is that the text is relatively large. For example how can I store the following XML piece in a j

4条回答
  •  感情败类
    2021-01-21 15:06

    I assume your question is how to take that exact string, and not one you retrieve from a web service or Ajax call or the like. While this is a pretty bad idea for lots of reasons, to answer the question...


    There is no really good way of doing this in JavaScript. Some browsers support line continuation by placing a \ at the end of the line, so you would do something like:

    var xml = '\
      \
        Game 01523, "X" to play\
        ...';
    

    But this is nonstandard, and in fact directly contradicts the JS spec:

    A 'LineTerminator' character cannot appear in a string literal, even if preceded by a backslash.

    The only really reliable way of doing this would be with manual string concatenation:

    var xml = '' + "\n" +
    '      ' + "\n" +
    '        Game 01523, "X" to play' + "\n" +
    '        ...';
    

    You can make this a bit neater like so:

    var xml = ['',
    '      ',
    '        Game 01523, "X" to play'
    '        ...'].join("\n");
    

    But it still sucks.

    Also, with all of these approaches, you would have to escape any single quotes, i.e. replace ' with \'. I didn't see any in your XML snippet at first glance though, which is good.

提交回复
热议问题