GithubHelp home page GithubHelp logo

ansi-regex's Introduction

ansi-regex

Regular expression for matching ANSI escape codes

Install

$ npm install ansi-regex

Usage

import ansiRegex from 'ansi-regex';

ansiRegex().test('\u001B[4mcake\u001B[0m');
//=> true

ansiRegex().test('cake');
//=> false

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

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

'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex());
//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007']

API

ansiRegex(options?)

Returns a regex for matching ANSI escape codes.

options

Type: object

onlyFirst

Type: boolean
Default: false (Matches any ANSI escape codes in a string)

Match only the first ANSI escape.

FAQ

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

Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.

On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.

Maintainers


Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.

ansi-regex's People

Contributors

akim95 avatar arjunmehta avatar cancerberosgx avatar kevva avatar litomore avatar qix- avatar richienb avatar samverschueren avatar sindresorhus avatar yetingli avatar zskycat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ansi-regex's Issues

Can't match this string "\u001b[?1049h\u001b[?1h\u001b="

"man" command in Linux will produce many escape codes. All of escape codes but this first string "\u001b[?1049h\u001b[?1h\u001b=" can be matched by ansi-regex.

I use strip-ansi to trim "\u001b[?1049h\u001b[?1h\u001b=" ,and get this result "�[?1049h�[?1h�=", not "".

IE problem

There is compatibility problem when I update the latest version, maybe the 'index.js' need to be transferred from ES6 to ES5

escape codes from `ansi-escapes` not being stripped by `strip-ansi`?

Hey, thanks for this useful tool!

If I understand correctly, the following escape codes should be stripped by strip-ansi, right?

const esc = require('ansi-escapes')
const stripAnsi = require('strip-ansi')

esc.scrollDown // '\u001b[T'
stripAnsi(esc.scrollDown) // '\u001b[T'
esc.beep // '\u0007'
stripAnsi(esc.beep) // '\u0007'

clearScreen gets stripped though:

esc.clearScreen // '\u001bc'
stripAnsi(esc.clearScreen) // ''

Not matching string

I thought this might be relevant here too. There is also another issue in chalk/strip-ansi#9
I'm having a super weird issue. I have this object that is has computed keys. I have things that I want to highlight in this object so it has chalk colors on some keys. This works great.
My object

let stats = {
    [user.name]: {
      Name: chalk.cyan(user['name'])
     //other properties
    }
  };

I want to print these values to a file and would like to strip the ANSI. However, the strip function does not seem to be working.

Here is what I'm using to print to file.

let stripped = stripAnsi(JSON.stringify(stats,null,2));
fs.writeFile('./stats.json', stripped, function(err) {
  if (err) {
    return console.log(err);
  }
  console.log('Stats saved to file!');
});

The output looks like this

{
  "John": {
    "Name": "\u001b[36mJohn\u001b[39m"
  }
}

I did some debugging and the string checks in strip-ansi seem to be working. I thought you might have a better idea of what exactly is happening.

Thanks!

IE11 not supported

This package seems to be used on various front end related libraries storybook included. This is already reported in #17 and on chalk/strip-ansi#18 which both seem to be causing the problem.

Some vim (or iTerm2?) ANSI sequences not fully consumed

Hi there,

I've been playing around with your library, feeding it strings from iTerm2 using "Edit > Copy With Control Sequences", and I came across several that are not fully consumed by the regex.

They appear to be non-standard (I think — I'm not an expert), and while I copied them out of a vim session, I don't know whether iTerm2 is reporting the sequences as they were written, or giving me back its internal state (which presumably could differ?).

Anyway, here's what I'm opening in vim:

repro.tsx

interface TextPaneProps {
  label: string;
}

and here's what I'm getting out of the "Copy With Control Sequences" action:

�[0;101minterface�[0m �[0;104;1mTextPaneProps�[0m �[46;1;104;0m{�[0m
  �[0;104;1mlabel�[0m: �[0;38:5:121mstring�[0;101m;�[0m
�[46;1;104;0m}

The sequence coloring the word string (with an 8-bit color) uses both semicolons AND colon separators.

This sequence (and I've noticed a few others like it) are only consumed up until right before the first colon: https://regex101.com/r/5B3Hte/1

Thanks! Hope this helps.

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module

Getting this issue while running any yarn task
I have updated to 5.0.1 after yarn audit showed as a moderate fix.

Project Type: node express
Node Version: 14.18.0
Usage: typescript
Dependency: Internal to packages(eslint, nodemon, instana/collector)

      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/test/Practice/test/node_modules/ansi-regex/index.js
require() of ES modules is not supported.
require() of /Users/test/Practice/test/node_modules/ansi-regex/index.js from /Users/test/Practice/test/node_modules/wide-align/node_modules/strip-ansi/index.js is an ES module file as it is a .js file whose nearest parent package.json contains \"type\": \"module\" which defines all .js files in that package scope as ES modules.
Instead rename /Users/test/Practice/test/node_modules/ansi-regex/index.js to end in .cjs, change the requiring code to use import(), or remove \"type\": \"module\" from /Users/test/Practice/test/node_modules/ansi-regex/package.json.

    at new NodeError (internal/errors.js:322:7)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1102:13)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:93:18)
    at Object.<anonymous> (/Users/test/Practice/test/node_modules/wide-align/node_modules/strip-ansi/index.js:2:19)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)

$ yarn audit
yarn audit v1.22.11

┌───────────────┬──────────────────────────────────────────────────────────────┐
│ moderate      │  Inefficient Regular Expression Complexity in                │
│               │ chalk/ansi-regex                                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ ansi-regex                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=5.0.1                                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ eslint                                                       │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ eslint > strip-ansi > ansi-regex                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://www.npmjs.com/advisories/1002401                     │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ moderate      │  Inefficient Regular Expression Complexity in                │
│               │ chalk/ansi-regex                                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ ansi-regex                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=5.0.1                                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ eslint                                                       │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ eslint > table > string-width > strip-ansi > ansi-regex      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://www.npmjs.com/advisories/1002401                     │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ moderate      │  Inefficient Regular Expression Complexity in                │
│               │ chalk/ansi-regex                                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ ansi-regex                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=5.0.1                                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ nodemon                                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ nodemon > update-notifier > boxen > ansi-align >             │
│               │ string-width > strip-ansi > ansi-regex                       │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://www.npmjs.com/advisories/1002401                     │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ moderate      │  Inefficient Regular Expression Complexity in                │
│               │ chalk/ansi-regex                                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ ansi-regex                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=5.0.1                                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ @instana/collector                                           │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ @instana/collector > @instana/shared-metrics > node-gyp >    │
│               │ npmlog > gauge > wide-align > string-width > strip-ansi >    │
│               │ ansi-regex                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://www.npmjs.com/advisories/1002401                     │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ moderate      │  Inefficient Regular Expression Complexity in                │
│               │ chalk/ansi-regex                                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ ansi-regex                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=5.0.1                                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ @instana/collector                                           │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ @instana/collector > @instana/autoprofile > node-gyp >       │
│               │ npmlog > gauge > wide-align > string-width > strip-ansi >    │
│               │ ansi-regex                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://www.npmjs.com/advisories/1002401                     │
└───────────────┴──────────────────────────────────────────────────────────────┘

Getting Lint error for the same

$ yarn lint --fix
yarn run v1.22.11
$ eslint src --ext .js,.ts,.tsx --fix
There was a problem loading formatter: /Users/test/Practice/test/node_modules/eslint/lib/cli-engine/formatters/stylish
Error: Must use import to load ES Module: /Users/test/Practice/test/node_modules/ansi-regex/index.js
require() of ES modules is not supported.
require() of /Users/test/Practice/test/node_modules/ansi-regex/index.js from /Users/test/Practice/test/node_modules/eslint/node_modules/strip-ansi/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename /Users/test/Practice/test/node_modules/ansi-regex/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/test/Practice/test/node_modules/ansi-regex/package.json.

React [CRA] - Don't work with 5.0.1

/usr/local/bin/node /Users/user/.yarn/bin/yarn.js run start
**yarn run v1.22.15**
$ react-scripts start
/Users/user/project/node_modules/renderkid/node_modules/strip-ansi/index.js:2
var ansiRegex = require('ansi-regex')();
                ^

Only works with version 2.0.0 without errors and vulnerabilities.

Tests for CVE-2021-3807

It'd probably be a good idea to add tests to make sure the changes that fixed CVE-2021-3807 don't regress in the future. I'll work on this in my fork and mention it in my PR.

This Library doesn't support CJS anymore

This library dropped the support for CJS, and from that time it's causing multiple issues, most managers download newer version which breaks when using require

Not matching certain ANSI escape codes

Hi there, I'm using your strip-ansi module, and I understand it is using this module to find ANSI codes to strip.

I encountered a problem where a code used by mocha, \u001b[0G is not being stripped/found using your regex.

I see the regex is /\u001b\[([0-9]{1,3}(;[0-9]{1,3})*)?[m|K]/g;. I wonder if adding a |G might help with this particular issue, but I think there are a whole plethora of other codes being missed by this. I am not sure which ANSI escape codes you would want to support, but here is a pretty comprehensive list of VT100 codes: http://ascii-table.com/ansi-escape-sequences-vt-100.php

I can help if you'd like!

Thanks!
Arjun

npm install fails

[email protected] node_modules/elasticsearch/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex -> node_modules/ansi-regex
- [email protected] node_modules/elasticsearch/node_modules/bluebird
- [email protected] node_modules/elasticsearch/node_modules/chalk/node_modules/ansi-styles
- [email protected] node_modules/elasticsearch/node_modules/chalk/node_modules/escape-string-regexp
- [email protected] node_modules/elasticsearch/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex
- [email protected] node_modules/elasticsearch/node_modules/chalk/node_modules/strip-ansi
- [email protected] node_modules/elasticsearch/node_modules/chalk
- [email protected] node_modules/elasticsearch/node_modules/lodash-compat
[email protected] node_modules/elasticsearch/node_modules/forever-agent -> node_modules/forever-agent
[email protected] node_modules/elasticsearch/node_modules/chalk/node_modules/has-ansi -> node_modules/has-ansi
[email protected] node_modules/elasticsearch/node_modules/lodash -> node_modules/lodash
[email protected] node_modules/elasticsearch/node_modules/chalk/node_modules/supports-color -> node_modules/supports-color
[email protected] /opt/jopplibot
+-- [email protected]  extraneous
+-- [email protected]  extraneous
+-- [email protected]  extraneous
`-- [email protected]  extraneous

npm WARN enoent ENOENT: no such file or directory, open '/opt/jopplibot/node_modules/app/package.json'
npm WARN [email protected] No repository field.
npm ERR! Linux 3.16.0-4-amd64
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install"
npm ERR! node v6.2.0
npm ERR! npm  v3.8.9
npm ERR! path /opt/jopplibot/node_modules/elasticsearch/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename

npm ERR! enoent ENOENT: no such file or directory, rename '/opt/jopplibot/node_modules/elasticsearch/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex' -> '/opt/jopplibot/node_modules/ansi-regex'
npm ERR! enoent ENOENT: no such file or directory, rename '/opt/jopplibot/node_modules/elasticsearch/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex' -> '/opt/jopplibot/node_modules/ansi-regex'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! Please include the following file with any support request:
npm ERR!     /opt/jopplibot/npm-debug.log

npm info lifecycle [email protected]~start: Failed to exec start script
npm ERR! Linux 3.16.0-4-amd64
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.2.0
npm ERR! npm  v3.8.9
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `npm install && node node_modules/app/main.js`
npm ERR! Exit status 254
npm ERR! 
npm ERR! Failed at the [email protected] start script 'npm install && node node_modules/app/main.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the joppli-bot package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm install && node node_modules/app/main.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs joppli-bot
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls joppli-bot
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /opt/jopplibot/npm-debug.log

Backport of security patch, for benefit of yargs

I know it's a pain in the neck, but would you consider back-porting #37 to the 5.x.x release line, for the benefit of yargs.

Yargs is making the effort during the transition to ESM to support both CJS and ESM, which makes us unable to update to the latest version of string-width.

If you were willing to make an exception (I know you're pushing folks towards using ESM exclusively) it would be really valuable for yargs users using CJK character sets.

Set title mode escape codes not matched

Hello,

according to links below, the following sequence instruct the terminal to set window title and icon:

\u001b]0;sg@tota:~/git/\u0007

and strip-ansi is not removing it

In other words I expect

stripAnsi('\u001b]0;sg@tota:~/git/\u0007\u001b[01;32m[sg@tota\u001b[01;37m misc-tests\u001b[01;32m]$') 

to return the string:

[sg@tota misc-tests]$

This is very common in xterm based linux stdout to print the prompt. Thanks BTW this is great project! keep it up!

References:
http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Title-Modes
https://unix.stackexchange.com/questions/288996/what-u001b0kubajcubic-u0007-escape-code-do

failing test PR https://github.com/chalk/ansi-regex/pull/22/files

Yarn audit fails due to vulnrability

Info: GHSA-93q8-gq69-wqmw

┌───────────────┬──────────────────────────────────────────────────────────────┐
│ moderate      │  Inefficient Regular Expression Complexity in                │
│               │ chalk/ansi-regex                                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ ansi-regex                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=5.0.1                                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ semantic-release                                             │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ semantic-release > @semantic-release/npm > npm > npmlog >    │
│               │ gauge > string-width > strip-ansi > ansi-regex               │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://www.npmjs.com/advisories/1002401                     │
└───────────────┴──────────────────────────────────────────────────────────────┘

does not work ie11

It does not work on ie11.
It can be used after modifying the arrow function to a general function.

index.js
module.exports = () => { 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'); };

modified..
module.exports = function () { 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'); };

Does not work on terminal-link

This bug only appears on iTerm 2.

How to reproduce

const terminalLink = require('terminal-link');
const stripAnsi = require('strip-ansi');

const link = terminalLink('click', 'https://github.com', {fallback: text => text});

console.log(stripAnsi(link));

Expected ouput

click

Actual output

ttps://github.com/sindresorhusclick

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.