Skip to content

Instantly share code, notes, and snippets.

@mudge
Created July 11, 2011 15:06
Show Gist options
  • Save mudge/1076046 to your computer and use it in GitHub Desktop.
Save mudge/1076046 to your computer and use it in GitHub Desktop.
JavaScript version of ActiveSupport's to_sentence method.
function toSentence(array) {
var wordsConnector = ", ",
twoWordsConnector = " and ",
lastWordConnector = ", and ",
sentence;
switch(array.length) {
case 0:
sentence = "";
break;
case 1:
sentence = array[0];
break;
case 2:
sentence = array[0] + twoWordsConnector + array[1];
break;
default:
sentence = array.slice(0, -1).join(wordsConnector) + lastWordConnector + array[array.length - 1];
break;
}
return sentence;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment