Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get my array as a *nice* human readable list in JavaScript?

Tags:

javascript

I have a list of allowed file extensions that can be uploaded to my site.

I check them with jQuery Validation plugin.

I'm displaying an error message if they choose a non supported extension.

It looks like

var msg = 'You may only upload files of type ' + allowedExt.join(', ');

Obviously the list doesn't look too flash. I'd like it to look more human readable.

Any way to do this?

like image 537
alex Avatar asked Sep 22 '10 00:09

alex


1 Answers

A simpler way to do the answer posted by alex is by using .pop() to get the last element off:

var niceList = function(array, join, finalJoin) {
    var arr = array.slice(0), last = arr.pop();
    join = join || ', ';
    finalJoin = finalJoin || ' and ';
    return arr.join(join) + finalJoin + last;    
};
like image 124
Nick Craver Avatar answered Oct 01 '22 20:10

Nick Craver