项目作者: kjirou

项目描述 :
Slice a string included ANSI escape codes
高级语言: JavaScript
项目地址: git://github.com/kjirou/slice-ansi-string.git
创建时间: 2017-12-23T04:30:19Z
项目社区:https://github.com/kjirou/slice-ansi-string

开源协议:MIT License

下载


slice-ansi-string

npm version
Build Status

Slice a string included ANSI escape codes

In some use cases slice-ansi did not work properly.
This is what I reworked with reference to slice-ansi.

Installation

  1. npm install slice-ansi-string

Usage

Basic usage

  1. const sliceAnsiString = require('slice-ansi-string');
  2. const str = 'A\u001b[31mBC\u001b[39mD'; // Meaning like "A<red>BC</red>D"
  3. console.log(sliceAnsiString(str, 0, 1)); // -> "A"
  4. console.log(sliceAnsiString(str, 0, 2)); // -> "A\u001b[31mB\u001b[39m", meaning like "A<red>B</red>"
  5. console.log(sliceAnsiString(str, 2, 3)); // -> "\u001b[31mC\u001b[39m", meaning like "<red>C</red>"

Nested ANSI escape codes

  1. const sliceAnsiString = require('slice-ansi-string');
  2. const str = 'A\u001b[31mB\u001b[4mCD\u001b[24m\u001b[39mE'; // Meaning like "A<red>B<underline>CD</underline></red>E"
  3. console.log(sliceAnsiString(str, 1, 3)); // -> "\u001b[31mB\u001b[4mC\u001b[24m\u001b[39m", meaning like "<red>B<underline>C</underline></red>"

API

sliceAnsiString(str, beginSlice, [endSlice])

Arguments

  • str: string
  • beginSlice: number
    • A zero-based index of where to begin the slice.
    • Only 0 or more.
  • endSlice: (string|null|undefined)
    • A zero-based index of where to end the slice.
    • Only 0 or more.
    • The default is until the end.

Supplements

  • Multibyte characters and surrogate pairs are counted as one character.
  • It may not be possible to correspond to the character string output by chalk.
    • For example, chalk.dim.bold('A') outputs "\u001b[2m\u001b[1mA\u001b[2m\u001b[22m", but this library expects "\u001b[2m\u001b[1mA\u001b[22m\u001b[22m".
    • However, chalk.bold.underline.red('A') returns expected outputs, so it may be a specific problem of dim.bold.