Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@ _.chop('whitespace', 3)
=> ['whi','tes','pac','e']
```

**rchop** _.rchop(string, step)

```javascript
_.rchop('whitespace', 3)
=> ['w', 'hit', 'esp', 'ace']
```

**clean** _.clean(str)

Compress some whitespaces to one.
Expand Down
8 changes: 8 additions & 0 deletions lib/underscore.string.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,13 @@
return step > 0 ? str.match(new RegExp('.{1,' + step + '}', 'g')) : [str];
},

rchop: function(str, step){
if (str == null) return [];
str = String(str);
step = ~~step;
return step > 0 ? str.match(new RegExp('(.{1,' + step + '})(?=(?:.{' + step + '})*$)', 'g')) : [str];
},

clean: function(str){
return _s.strip(str).replace(/\s+/g, ' ');
},
Expand Down Expand Up @@ -641,6 +648,7 @@

// Aliases

_s.lchop = _s.chop;
_s.strip = _s.trim;
_s.lstrip = _s.ltrim;
_s.rstrip = _s.rtrim;
Expand Down
6 changes: 3 additions & 3 deletions test/speed.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@
});

JSLitmus.test('succ', function(){
var let = 'a', alphabet = [];
var ch = 'a', alphabet = [];

for (var i=0; i < 26; i++) {
alphabet.push(let);
let = _(let).succ();
alphabet.push(ch);
ch = _(ch).succ();
}

return alphabet;
Expand Down
11 changes: 11 additions & 0 deletions test/strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,17 @@ $(document).ready(function() {
ok(_(12345).chop(1).length === 5, 'output [1, 2, 3, 4, 5]');
});

test('String: rchop', function(){
ok(_('whitespace').rchop(2).length === 5, 'output [wh, it, es, pa, ce]');
ok(_('whitespace').rchop(3).length === 4, 'output [w, hit, esp, ace]');
ok(_('whitespace').rchop()[0].length === 10, 'output [whitespace]');
ok(_('whitespace').rchop(-1)[0].length === 10, 'output [whitespace]');
ok(_('whitespace').rchop(NaN)[0].length === 10, 'output [whitespace]');
ok(_('whitespace').rchop(null)[0].length === 10, 'output [whitespace]');
ok(_('whitespace').rchop({})[0].length === 10, 'output [whitespace]');
ok(_(12345).rchop(1).length === 5, 'output [1, 2, 3, 4, 5]');
});

test('String: clean', function(){
equal(_.clean(' foo bar '), 'foo bar');
equal(_.clean(''), '');
Expand Down