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!
asked May 17, 2012 at 17:38
fancy
52k64 gold badges159 silver badges231 bronze badges
3 Answers 3
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(', ');
answered May 17, 2012 at 17:42
jmar777
39.8k11 gold badges68 silver badges66 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
HBP
But it does change the array which might cause problems downstream. Also does not quite work for arrays of length 1.
jmar777
I guess if that's a problem you can just do
array2 = array.slice();jmar777
Good point though - I should have mentioned that my approach isn't side-effect free.
jmar777
Added two alternative approaches - one with regular expressions, and another one that does array manip, but leaves
array intact.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"]
answered May 17, 2012 at 18:21
HBP
16.1k6 gold badges30 silver badges34 bronze badges
Comments
var output = array.join(", ");
output = outsput.substr(0, output.lastIndexOf(", ") + " and " + output.substr(output.lastIndexOf(" and "));
answered May 17, 2012 at 17:39
Elliot Bonneville
53.6k24 gold badges101 silver badges125 bronze badges
Comments
lang-js