Skip to content

Commit eac826a

Browse files
ZSkycatsindresorhus
authored andcommittedSep 18, 2018
Add option to only match the first occurrence (#24)
Fixes #23
1 parent 385eca9 commit eac826a

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed
 

‎index.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
'use strict';
22

3-
module.exports = () => {
3+
const defaultOptions = {
4+
onlyFirst: false
5+
};
6+
7+
module.exports = options => {
8+
options = Object.assign({}, defaultOptions, options);
9+
410
const pattern = [
511
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)',
612
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
713
].join('|');
814

9-
return new RegExp(pattern, 'g');
15+
return new RegExp(pattern, options.onlyFirst ? undefined : 'g');
1016
};

‎readme.md

+19
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,28 @@ ansiRegex().test('cake');
2323

2424
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
2525
//=> ['\u001B[4m', '\u001B[0m']
26+
27+
'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true}));
28+
//=> ['\u001B[4m']
2629
```
2730

2831

32+
## API
33+
34+
### ansiRegex([options])
35+
36+
Returns a regex for matching ANSI escape codes.
37+
38+
#### options
39+
40+
##### onlyFirst
41+
42+
Type: `boolean`<br>
43+
Default: `false` *(Matches any ANSI escape codes in a string)*
44+
45+
Match only the first one.<br>
46+
47+
2948
## FAQ
3049

3150
### Why do you test for codes not in the ECMA 48 standard?

‎test.js

+4
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ test('match clear screen in a string', t => {
3737
t.is('foo\u001B[2Jbar'.match(m())[0], '\u001B[2J');
3838
});
3939

40+
test('match only first', t => {
41+
t.is('foo\u001B[4mcake\u001B[0m'.match(m({onlyFirst: true})).length, 1);
42+
});
43+
4044
test.failing('match "change icon name and window title" in string', t => {
4145
t.is('\u001B]0;sg@tota:~/git/\u0007\u001B[01;32m[sg@tota\u001B[01;37m misc-tests\u001B[01;32m]$'.match(m())[0], '\u001B]0;sg@tota:~/git/\u0007');
4246
});

0 commit comments

Comments
 (0)
Please sign in to comment.