Skip to content

Commit

Permalink
Add option to only match the first occurrence (#24)
Browse files Browse the repository at this point in the history
Fixes #23
  • Loading branch information
ZSkycat authored and sindresorhus committed Sep 18, 2018
1 parent 385eca9 commit eac826a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
10 changes: 8 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
'use strict';

module.exports = () => {
const defaultOptions = {
onlyFirst: false
};

module.exports = options => {
options = Object.assign({}, defaultOptions, options);

const pattern = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
].join('|');

return new RegExp(pattern, 'g');
return new RegExp(pattern, options.onlyFirst ? undefined : 'g');
};
19 changes: 19 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,28 @@ ansiRegex().test('cake');

'\u001B[4mcake\u001B[0m'.match(ansiRegex());
//=> ['\u001B[4m', '\u001B[0m']

'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true}));
//=> ['\u001B[4m']
```


## API

### ansiRegex([options])

Returns a regex for matching ANSI escape codes.

#### options

##### onlyFirst

Type: `boolean`<br>
Default: `false` *(Matches any ANSI escape codes in a string)*

Match only the first one.<br>


## FAQ

### Why do you test for codes not in the ECMA 48 standard?
Expand Down
4 changes: 4 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ test('match clear screen in a string', t => {
t.is('foo\u001B[2Jbar'.match(m())[0], '\u001B[2J');
});

test('match only first', t => {
t.is('foo\u001B[4mcake\u001B[0m'.match(m({onlyFirst: true})).length, 1);
});

test.failing('match "change icon name and window title" in string', t => {
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');
});
Expand Down

0 comments on commit eac826a

Please sign in to comment.