0
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!

3 Answers 3

4

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(', ');
Sign up to request clarification or add additional context in comments.

4 Comments

But it does change the array which might cause problems downstream. Also does not quite work for arrays of length 1.
I guess if that's a problem you can just do array2 = array.slice();
Good point though - I should have mentioned that my approach isn't side-effect free.
Added two alternative approaches - one with regular expressions, and another one that does array manip, but leaves array intact.
1

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"]

Comments

0
var output = array.join(", ");
output = outsput.substr(0, output.lastIndexOf(", ") + " and " + output.substr(output.lastIndexOf(" and "));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.