Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Javascript array into a readable string

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

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

...what is the most elegant way you have found to convert that list to a readable english phrase of the form:

"item1, item2, item3 and item4"

The function must also work with:

var myStrings = ["item1"]; // produces "item1"
var myStrings = ["item1", "item2"]; // produces "item1 and item2"
like image 731
Mark Robinson Avatar asked Jan 24 '11 14:01

Mark Robinson


People also ask

How do you turn an array into a string in JavaScript?

Array.prototype.join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Which method converts an array to string in JavaScript?

prototype. toString() The toString() method returns a string representing the specified array and its elements.

How do I convert an array of numbers to strings?

To convert an array of numbers to an array of strings, call the map() method on the array, and on each iteration, convert the number to a string. The map method will return a new array containing only strings.


1 Answers

Like this:

a.length == 1 ? a[0] : [ a.slice(0, a.length - 1).join(", "), a[a.length - 1] ].join(" and ")
like image 144
SLaks Avatar answered Nov 15 '22 04:11

SLaks