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

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

I test them using the jQuery validation plugin .

I am showing an error message if they select an unsupported extension.

Similar to

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

Obviously, the list does not look too bright. I would like it to look more humane readable.

How to do it?

+4
source share
6 answers

An easier way to make an answer posted by alex is .pop() to disable the last element:

 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; }; 
+8
source

The accepted answer does not do very well with one list of positions.

 function niceList(array) { if (!array || array.length == 0) return ""; var clone = array.slice(0); return function build() { if (clone.length == 1) return clone[0]; if (clone.length == 2) return clone[0] + ' and ' + clone[1]; return clone.shift() + ", " + build(); }(); } 
+4
source

Another way to do this.

Cases considered:

  • [] → ""
  • ["] →" "
  • ["A"] → "A"
  • ["A", "B"] → "A and B"
  • ["A", "B", "C"] → "A, B and C"

... etc.

 function niceList(a) { return [ a /* Get all the elements except the last one. * If there is just one element, get that */ .slice(0, a.length - 1 || 1) /* Create a comma separated string from these elements */ .join(", ") ] /* Process the last element (if there is one) and concat it * with the processed first part. */ .concat( a /* Create a copy */ .slice() /* Take the last element, if there is one */ .splice(-1, Number(a.length > 1)) ) /* Join the two processed parts */ .join(" and "); } 
+4
source

Yes, you can!

 var niceList = function(array, join, finalJoin) { join = join || ', '; finalJoin = finalJoin || ' and '; var length = array.length; return array.slice(0, length - 1).join(join) + finalJoin + array[length - 1]; }; alert(niceList([a, b, c])); // 'a, b and c' 
+2
source

Since we, apparently, provide different answers for alex, here is one without join :

 function niceList(array, join, final) { return array.reduce(function (pv, cv, i, a) { return pv + (i == a.length - 1 ? final : join) + cv; }); }; 

Does not work with older browsers, etc.

+1
source

I took you literally and turned it into an actual HTML list.

 var extensions = ['html', 'txt', 'png', 'jpg']; var extension_list = '<ul>'; for(i=0; i<extensions.length; i++) { extension_list += '<li>'+extensions[i]+'</li>'; } extension_list += '<ul>'; var msg = '<p>Sorry, you can only upload the following extensions:</p>'+extension_list; 
0
source

All Articles