Convert Javascript array to readable string

If you have an array of strings in JavaScript / jQuery:

var myStrings = ["item1", "item2", "item3", "item4"];

... which is the most elegant way you have found to convert this list into a readable English phrase of the form:

"item1, item2, item3 and item4"

The function should also work with:

var myStrings = ["item1"]; // produces "item1"
var myStrings = ["item1", "item2"]; // produces "item1 and item2"
+3
source share
1 answer

Like this:

a.length == 1 ? a[0] : [ a.slice(0, a.length - 1).join(", "), a[a.length - 1] ].join(" and ")
+10
source

Source: https://habr.com/ru/post/1787466/


All Articles