From eac826a340f4e292815e4425ee670d42cae38c23 Mon Sep 17 00:00:00 2001 From: ZSkycat Date: Tue, 18 Sep 2018 16:05:49 +0800 Subject: [PATCH] Add option to only match the first occurrence (#24) Fixes #23 --- index.js | 10 ++++++++-- readme.md | 19 +++++++++++++++++++ test.js | 4 ++++ 3 files changed, 31 insertions(+), 2 deletions(-) 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'); });