Skip to content

Commit cb32d86

Browse files
committed
Add match string filter (cf #68)
1 parent 6d3c32a commit cb32d86

File tree

4 files changed

+60
-0
lines changed

4 files changed

+60
-0
lines changed

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
- [stripTags](#striptags)
5252
- [stringular](#stringular)
5353
- [test](#test)
54+
- [match](#match)
5455
- [trim](#trim)
5556
- [ltrim](#ltrim)
5657
- [rtrim](#rtrim)
@@ -1086,8 +1087,18 @@ Test if a string match a pattern<br/>
10861087
**Usage:** ```string | test: pattern: flag[optional]```
10871088
```html
10881089
<p>{{ '15/12/2003' | test: '^[0-9]{2}[/]{1}[0-9]{2}[/]{1}[0-9]{4}$': 'i' }}</p>
1090+
<p>{{ '0123456' | test: '\\D': 'i' }}</p>
10891091
<!--result:
10901092
true
1093+
true
1094+
```
1095+
###match
1096+
Return an array of matched element in a string<br/>
1097+
**Usage:** ```string | match: pattern: flag[optional]```
1098+
```html
1099+
<p>{{ '15/12/2003' | match: '\\d+': 'g' }}</p>
1100+
<!--result:
1101+
['15', '12', '2003']
10911102
```
10921103
#Math
10931104

src/_filter/string/match.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @ngdoc filter
3+
* @name match
4+
* @kind function
5+
*
6+
* @description
7+
* Return the matched pattern in a string.
8+
*/
9+
angular.module('a8m.match', [])
10+
11+
.filter('match', function () {
12+
return function (input, pattern, flag) {
13+
14+
var reg = new RegExp(pattern, flag);
15+
16+
return isString(input)
17+
? input.match(reg)
18+
: null;
19+
}
20+
});

src/filters.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ angular.module('angular.filter', [
2323
'a8m.rtrim',
2424
'a8m.repeat',
2525
'a8m.test',
26+
'a8m.match',
2627

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

test/spec/filter/string/match.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'use strict';
2+
3+
describe('matchFilter', function () {
4+
5+
var filter;
6+
7+
beforeEach(module('a8m.match'));
8+
9+
beforeEach(inject(function ($filter) {
10+
filter = $filter('match');
11+
}));
12+
13+
it('should test a string with given pattern', function() {
14+
15+
expect(filter('15/12/2003', '\\d+', 'g')).toEqual(['15', '12', '2003']);
16+
expect(angular.equals(filter('foobarbaz', '[a-z]{3}'), ['foo'])).toBeTruthy();
17+
expect(filter('foobarbaz', '[a-z]{3}', 'g')).toEqual(['foo', 'bar', 'baz']);
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)