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.

1

3 Answers 3

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

Any ideas why format is not there as part of javascript core functionality?
Ecma did probably not consider it necessary. It's easy to implement yourself, as you see above.
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); 

1 Comment

Do you think I could use javascript formatting instead? I've almost no knowledge of javascript so I will have to look into that?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.