Mastering Wrap ANSI for Efficient Terminal String Wrapping and Formatting

Introduction to Wrap ANSI

Wrap ANSI is a powerful utility for wrapping terminal strings with ANSI escape codes. It helps maintain the visual formatting of terminal output without disrupting the ANSI codes.

API Examples of Wrap ANSI

Basic Example

  const wrapAnsi = require('wrap-ansi');

  const input = 'The quick brown fox jumps over the lazy dog.';
  const wrappedText = wrapAnsi(input, 20);
  console.log(wrappedText);

This example wraps the input string at a width of 20 characters.

Handling ANSI Escape Codes

  const input = '\u001b[31mThe quick brown fox \u001b[39m jumps over the lazy dog.';
  const wrappedText = wrapAnsi(input, 20);
  console.log(wrappedText);

This example demonstrates the handling of ANSI escape codes while wrapping the text.

Word-Wrapping With Preserve Words

  const wrappedText = wrapAnsi('Hello World', 5, { hard: true });
  console.log(wrappedText);

This example forces word wrapping without breaking words unless necessary.

Options for Wrapping

wrap-ansi supports several options to control the behavior of wrapping:

  • trim: Blanks out lines of empty spaces.
  • hard: Hard-wrap the text, breaking words if necessary.
  • wordWrap: Maintains word boundaries when possible.

Sample Application Using Wrap ANSI

  const wrapAnsi = require('wrap-ansi');
  const chalk = require('chalk');

  const text = chalk.green('This is a long message that needs to be wrapped properly while preserving ANSI codes.');

  function formatWrappedText(text, width) {
    return wrapAnsi(text, width, { hard: true, trim: true });
  }

  console.log(formatWrappedText(text, 50));

This application wraps a colored text message at 50 characters width.

This example combines wrap-ansi with chalk for enhanced terminal text formatting.

For more advanced usage, refer to the official Wrap ANSI documentation and explore other options and features available.


Hash: 04ed2790ae60f67535218d79753dffa072ff981848b5add86d1e4f8072cd0889

Leave a Reply

Your email address will not be published. Required fields are marked *