Created
October 5, 2011 06:55
-
-
Save mihar/1263820 to your computer and use it in GitHub Desktop.
JavaScript equivalent of Array#to_sentence from Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.to_sentence = function() { | |
return this.join(", ").replace(/,\s([^,]+)$/, ' and $1') | |
} |
Nice but would recommend https://gist.github.com/mudge/1076046 for a more complete version.
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
Thanks! I ported it to CoffeeScript:
Array.prototype.to_sentence = () ->
this.join(", ").replace(/,\s([^,]+)$/, ' and $1')