Skip to content

Commit b4a5e94

Browse files
committed
added split filter with test
1 parent 43a4a04 commit b4a5e94

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

src/_filter/string/split.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @ngdoc filter
3+
* @name split
4+
* @kind function
5+
*
6+
* @description
7+
* split a string by a provided delimiter (none '' by default) and skip first n-delimiters
8+
*/
9+
angular.module('a8m.split', [])
10+
.filter('split', function () {
11+
function escapeRegExp(str) {
12+
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
13+
}
14+
15+
return function (input, delimiter, skip) {
16+
var _regexp, _matches, _splitted, _temp;
17+
18+
if (isUndefined(input) || !isString(input)) {
19+
return null;
20+
}
21+
if (isUndefined(delimiter)) delimiter = '';
22+
if (isNaN(skip)) skip = 0;
23+
24+
_regexp = new RegExp(escapeRegExp(delimiter), 'g');
25+
_matches = input.match(_regexp);
26+
27+
if (isNull(_matches) || skip >= _matches.length) {
28+
return [input];
29+
}
30+
31+
if (skip === 0) return input.split(delimiter);
32+
33+
_splitted = input.split(delimiter);
34+
_temp = _splitted.splice(0, skip + 1);
35+
_splitted.unshift(_temp.join(delimiter));
36+
37+
return _splitted;
38+
};
39+
})
40+
;

src/filters.js

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ angular.module('angular.filter', [
2424
'a8m.repeat',
2525
'a8m.test',
2626
'a8m.match',
27+
'a8m.split',
2728

2829
'a8m.to-array',
2930
'a8m.concat',

test/spec/filter/string/split.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'use strict';
2+
3+
describe('splitFilter', function () {
4+
5+
var filter, sentence = "Today is a beautiful and sunny day!";
6+
7+
beforeEach(module('a8m.split'));
8+
9+
beforeEach(inject(function ($filter) {
10+
filter = $filter('split');
11+
}));
12+
13+
it('should test a string with given pattern', function() {
14+
15+
expect(filter(sentence, ' ', 3)).toEqual(['Today is a beautiful', 'and', 'sunny', 'day!']);
16+
expect(angular.equals(filter(sentence, '.'), [sentence])).toBeTruthy();
17+
expect(filter(sentence, ' ')).toEqual(['Today', 'is', 'a', 'beautiful', 'and', 'sunny', 'day!']);
18+
19+
});
20+
21+
it('should get a !string and return null', function() {
22+
expect(filter({})).toEqual(null);
23+
expect(filter([])).toEqual(null);
24+
expect(filter(1)).toEqual(null);
25+
expect(filter(!1)).toBeFalsy(null);
26+
});
27+
28+
});

0 commit comments

Comments
 (0)