diff --git a/README.markdown b/README.markdown index e98b4c2f..5d63032d 100644 --- a/README.markdown +++ b/README.markdown @@ -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. diff --git a/lib/underscore.string.js b/lib/underscore.string.js index a559f930..1637709e 100644 --- a/lib/underscore.string.js +++ b/lib/underscore.string.js @@ -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, ' '); }, @@ -641,6 +648,7 @@ // Aliases + _s.lchop = _s.chop; _s.strip = _s.trim; _s.lstrip = _s.ltrim; _s.rstrip = _s.rtrim; diff --git a/test/speed.js b/test/speed.js index 9ceeea76..0cee3f51 100644 --- a/test/speed.js +++ b/test/speed.js @@ -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; diff --git a/test/strings.js b/test/strings.js index 77364f20..4dcfb41b 100644 --- a/test/strings.js +++ b/test/strings.js @@ -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(''), '');