0

I have the following code:

$("#stats-list")
    .append("<li>Elapsed: " + ajaxElapsed + "</li>\n" +
            "<li>Display: " + tableElapsed + "</li>\n" +
            "<li>Total:   " + (ajaxElapsed + tableElapsed) + "</li>");

This was originally three appends that I concatenated into one. Is there anything I could do with jQuery that would clean up this code even more. What I was wondering was if jQuery has any string formatting with tokens that I could use.

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • This http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format and this http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery look like what you are asking for. – Ilia Frenkel Sep 14 '12 at 06:12

3 Answers3

2
function format(formatString) {
    var args = Array.prototype.slice.call(arguments,1);
    return formatString.replace(/\{(\d+)\}/g, function(match, num) {
      return args[Number(num)];
    });
}

format("<li>Elapsed: {0}</li>\n<li>Display: {1}</li>\n<li>Total:   {2}</li>",
    ajaxElapsed, tableElapsed, ajaxElapsed + tableElapsed);
Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
1

afaik there is none built-in, but a powerful templating-subsystem, see jQuery Templates

just for completeness, i think this could be done more elegant:

var list = $('#stats-list');
$('<li />').text('Elapsed: ' + ajaxElapsed).appendTo(list);
$('<li />').text('Display: ' + tableElapsed).appendTo(list);
$('<li />').text('Total: ' + (ajaxElapsed + tableElapsed)).appendTo(list);
TheHe
  • 2,933
  • 18
  • 22
1

If you have many items you can do something like this to avoid missing + and writing li so many times. You can add any number of items inside the array and they will be joined with lis appropriately.

var list = '<li>' + [
  'Elapsed: ' + ajaxElapsed,
  'Display: ' + tableElapsed,
  'Total: ' + ajaxElapsed + tableElapsed
].join('</li><li>') + '</li>';

$("#stats-list").append(list);

As a note I wouldn't use \n. li is a block element by default, so you'd be better styling it with css.

elclanrs
  • 92,861
  • 21
  • 134
  • 171