Skip to content

Instantly share code, notes, and snippets.

@mihar
Created October 5, 2011 06:55
Show Gist options
  • Save mihar/1263820 to your computer and use it in GitHub Desktop.
Save mihar/1263820 to your computer and use it in GitHub Desktop.
JavaScript equivalent of Array#to_sentence from Rails
Array.prototype.to_sentence = function() {
return this.join(", ").replace(/,\s([^,]+)$/, ' and $1')
}
@ZenCocoon
Copy link

Nice but would recommend https://gist.github.com/mudge/1076046 for a more complete version.

@calebmeyer
Copy link

calebmeyer commented Jun 28, 2016

If you like oxford commas (my team at work does), you can do this instead:

Array.prototype.toSeries = function() {
  if this.length == 2 {
    return this.join(' and ');
  }
  return this.join(', ').replace(/,\s([^,]+)$/, ', and $1');
}

I also changed the name to toSeries because I disagree with rails about the name.

Coffeescript version:

Array::toSeries = -> if @length == 2 then @join(' and ') else @join(', ').replace(/,\s([^,]+)$/, ', and $1')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment