snowflakes74 snowflakes74 - 11 months ago 69
Javascript Question

Conditional array.join in Javascript

I have an array of strings and I would like to display them as a comma separated string but add "and" for the last element. For example I have

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(' ,');


'Banana, Orange, Apple, Mango'

Is there any way the I add "and" for the last word so it outputs

'Banana, Orange, Apple and Mango'

Answer Source

You can try this,

var delimitter = ', ';
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(delimitter); 
var index = energy.lastIndexOf(delimitter);
energy = energy.substring(0, index) + ' and ' + energy.substring(index + delimitter.length);