简体   繁体   中英

Breaking a string into multiple lines inside a javascript code

I am trying to format (beautify, tidy, clear up.. you name it) a snippet of HTML inside my javascript code or, in other words, spread it out on multiple lines rather than having it written on one line so it can be read easily.

Basically, it's a piece of html code that I am trying to append to the page by calling the jQuery's .append(); method.

And here's what I am trying to do:

$('.videos').append('<li>
                    <span>' + count + '</span> - 
                    <a href="' + vList[i].player + '">
                        <span class="title">' + videoTitle + '</span>
                    </a>
                    </li>');

Appearantly, it won't work that way. I am getting Uncaught SyntaxError: Unexpected token >

When It is written as follows, everything works fine.

$('.videos').append('<li><span>' + count + '</span> - <a href="' + vList[i].player + '"><span class="title">' + videoTitle + '</span></a></li>');

It's kind of weird that when I tried to do the exact thing here,

var albumURL = API + '/video.get?=owner_id=' + userID +
                     '&album_id=' + aList[i].album_id +
                     '&access_token=' + accessToken;

I had no problem at all.

I know this issue is not that big of a deal but I am trying to get around with it just for the sake of simplicity.

Any suggestions?

If you have a multiline string, you need to use the multiline string syntax .

However, it's better to store your HTML in templates and not code :) That makes them more readable, more reusable and more maintainable.

What about something like - in your HTML:

<script type="text/template" id="videoTemplate">
    <li>
      <span>{{count}}</span>
      <a href="{{videoURL}}">
        <span class="title">{{videoTitle}}</span>
      </a>
    </li>
</script>

Then in JavaScript

var template = $("#videoTemplate").html();
$(".videos").append(template.replace("{{count}}",count).
                             replace("{{videoURL}}",vList[i].player).
                             replace("{{videoTitle}}",videoTitle));

That way, you get a clearer separation of the template you're using and your code. You can change the HTML independently and reuse it in other parts of code more easily.

The code does not have to even be aware of template changes and a designer can change the design without knowing JavaScript.

Of course, if you find yourself doing this often you can use a templating engine and not having a .replace chain.

ES2015 also introduces template strings which are also kind of nice and serve the same purpose in principle:

 const videoTemplate = `<li>
      <span>${count}</span>
      <a href="${vList[i].player}">
        <span class="title">${videoTitle}</span>
      </a>
    </li>`;

If you want to write a multiline string you should use the "\\":

example:

$('.videos').append('<li> \
                <span>' + count + '</span> - \
                <a href="' + vList[i].player + '"> \
                    <span class="title">' + videoTitle + '</span> \
                </a> \
                </li>');

New answer:

With ES6 you can actually use string concatenation that is line-break insensible:

var html = `
    <li>
        ${count}
    </li>
`;

and the line breaks will not be a problem. Prior to ES6 I used mostly arrays and concat them. Its faster:

var html = [
    '<li>',
        count
    '</li>'
].join('');

Old answer:

In javascript you cannot break lines without concatenating them with a + or using \\ . Try this:

$('.videos').append('<li>' +
    '<span>' + count + '</span> - ' +
    '<a href="' + vList[i].player + '">' +
    '<span class="title">' + videoTitle + '</span>' +
    '</a>' +
    '</li>'); 

If you simply want to split rendered output onto new lines then append \\n where you want the newline to appear, like this...

$('.videos').append('<li>\n<span>' + count + '</span> -\n<a href="' + vList[i].player + '">\n<span class="title">' + videoTitle + '</span>\n</a>\n</li>\n');

And if you want your JS to look nice you could try this, which will also ensure that your rendered HTML is indented.

var item = '';

item += '<li>\n';
item += '    <span>' + count + '</span> -\n';
item += '    <a href="' + vList[i].player + '">\n';
item += '        <span class="title">' + videoTitle + '</span>\n';
item += '    </a>\n';
item += '</li>\n';

$('.videos').append(item);

you can try like this

$('.videos').append( ['<li>',
    '<span>' + count + '</span> - ' ,
    '<a href="' + vList[i].player + '">' ,
        '<span class="title">' + videoTitle + '</span>' ,
    '</a>' ,
'</li>'].join('') );

From New Perspectives on HTML5, CSS, and JavaScript 6th Edition , Chapter 9 Getting Started with JavaScript:

"If you want to break a text string into several lines, you can indicate that the text string continues on the next line by using the following backslash \\ character.

Example of proper line break:
window.alert("Welcome \\
to Tulsa");

If you are rendering HTML using backticks and want to pass a variable inside it's very easy just add the backticks around the variable and concatenate it. let's take an eye on the below example

var x = 1; 
$(wrapper).append(`
                <div class="card">
                   <div class="card-body">
                      <h5 class="card-title">Plot `+ x +` </h5>
                   </div>
                </div>
               `);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM