Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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-PRZcf-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