Reputation: 51463
array = ['item1', 'item2', 'item3', 'item4']
output = array.toString()
This gets me "item1,item2,item3,item4"
but I need to turn this into "item1, item2, item3, and item4"
with spaces and "and"
How could I construct a regex process to do this rather then substringing and find/replacing?
Is this the best way?
Thanks!
Upvotes: 0
Views: 100
Reputation: 16063
This version handles all the variations I could think of :
function makeList (a) {
if (a.length < 2)
return a[0] || '';
if (a.length === 2)
return a[0] + ' and ' + a[1];
return a.slice (0, -1).join (', ') + ', and ' + a.slice (-1);
}
console.log ([makeList ([]),
makeList (['One']),
makeList (['One', 'Two']),
makeList(['One', 'Two', 'Three']),
makeList(['One', 'Two', 'Three', 'Four'])]);
// Displays : ["", "One", "One and Two", "One, Two, and Three", "One, Two, Three, and Four"]
Upvotes: 1
Reputation: 39699
Try this:
var array = ['item1', 'item2', 'item3', 'item4'];
array.push('and ' + array.pop());
var output = array.join(', ');
// output = 'item1, item2, item3, and item4'
Edit: if you really do want a regex-based solution:
var output = array.join(',')
.replace(/([^,]+),/g, '$1, ').replace(/, ([^,]+)$/, ' and $1');
Another edit:
Here's another non-regex approach that doesn't mess with the original array
variable:
var output = array.slice(0,-1).concat('and ' + array.slice(-1)).join(', ');
Upvotes: 4
Reputation: 53371
var output = array.join(", ");
output = outsput.substr(0, output.lastIndexOf(", ") + " and " + output.substr(output.lastIndexOf(" and "));
Upvotes: 0