diff --git a/index.js b/index.js index 91a1594..e5d7d01 100644 --- a/index.js +++ b/index.js @@ -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'); }; diff --git a/readme.md b/readme.md index 22db1c3..353248e 100644 --- a/readme.md +++ b/readme.md @@ -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`
+Default: `false` *(Matches any ANSI escape codes in a string)* + +Match only the first one.
+ + ## FAQ ### Why do you test for codes not in the ECMA 48 standard? diff --git a/test.js b/test.js index 270b1a8..cd25205 100644 --- a/test.js +++ b/test.js @@ -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'); });