Skip to content

Commit

Permalink
Added toSentenceSerial method
Browse files Browse the repository at this point in the history
  • Loading branch information
rwz committed Aug 17, 2012
1 parent ed82250 commit 1104ea6
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
15 changes: 15 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,21 @@ _.toSentence(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt ')
=> 'jQuery, Mootools unt Prototype';
```

**toSentenceOxford** _.toSentenceOxford(array, [delimiter, lastDelimiter])

The same as `toSentence`, but adjusts delimeters to use [Serial comma](http://en.wikipedia.org/wiki/Serial_comma).

```javascript
_.toSentenceSerial(['jQuery', 'Mootools'])
=> 'Mootools and Prototype';

_.toSentenceSerial(['jQuery', 'Mootools', 'Prototype'])
=> 'jQuery, Mootools, and Prototype'

_.toSentenceSerial(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt ');
=> 'jQuery, Mootools, unt Prototype';
```

**repeat** _.repeat(string, count, [separator])

Repeats a string count times.
Expand Down
10 changes: 9 additions & 1 deletion lib/underscore.string.js
Original file line number Diff line number Diff line change
Expand Up @@ -473,14 +473,22 @@
return ~pos ? str.slice(0, pos) : str;
},

toSentence: function(array, separator, lastSeparator) {
toSentence: function(array, separator, lastSeparator, serial) {
separator = separator || ', '
lastSeparator = lastSeparator || ' and '
var a = array.slice(), lastMember = a.pop();

if (array.length > 2 && serial) lastSeparator = _s.rtrim(separator) + lastSeparator;

return a.length ? a.join(separator) + lastSeparator + lastMember : lastMember;
},

toSentenceSerial: function() {
var args = slice.call(arguments);
args[3] = true;
return _s.toSentence.apply(_s, args);
},

slugify: function(str) {
if (str == null) return '';

Expand Down
6 changes: 6 additions & 0 deletions test/strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,12 @@ $(document).ready(function() {
equals(_.toSentence(['jQuery', 'MooTools', 'Prototype'], ',', ' or '), 'jQuery,MooTools or Prototype', 'handles custom separators');
});

test('Strings: toSentenceSerial', function (){
equals(_.toSentenceSerial(['jQuery']), 'jQuery');
equals(_.toSentenceSerial(['jQuery', 'MooTools']), 'jQuery and MooTools');
equals(_.toSentenceSerial(['jQuery', 'MooTools', 'Prototype']), 'jQuery, MooTools, and Prototype');
});

test('Strings: slugify', function() {
equals(_('Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/').slugify(), 'jack-jill-like-numbers-123-and-4-and-silly-characters');
equals(_('Un éléphant à l\'orée du bois').slugify(), 'un-elephant-a-loree-du-bois');
Expand Down

0 comments on commit 1104ea6

Please sign in to comment.