Center text horizontally


Center text horizontally

This was built as part of a CLI presentation to horizontally center text. As a result, this will properly center ANSI colored text.

It was not designed to work with non-monospaced text.

Install the module with: npm install center-text

// In an 40 column terminal 
var centerText = require('center-text');
centerText('Hello World!');
// Returns '              Hello World!              '; 

center-text exposes a function, centerText, as its module.exports.

Return string of centered text

  • text String - Content to center
  • options Object
    • columns Number - Amount of columns to center between. If not provided, process.stdout.columns will be used.
    • leftBias Boolean - If truthy, uneven offsets will pad to the right more than the left.

An example of leftBias in action:

centerText('aa', {
  columns: 3
// Returns ' aa' 
centerText('aa', {
  columns: 3,
  leftBias: true
// Returns 'aa ' 

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint via grunt and test via npm test.

Support this project and others by twolfson via gittip.

As of Nov 30 2013, Todd Wolfson has released this repository and its contents to the public domain.

It has been released under the UNLICENSE.