dthree
dthree

Reputation: 20790

Node console logging with colors - char length

Using the colors node module, I could do this:

var foo = "bar".cyan;

Now, instead of having a length of 3, foo has a length of 13 because of the colors:

foo.length; // -> 13
util.inspect(foo); // -> '\u001b[36mfoo\u001b[39m'

I'm trying to do fancy console logging that deals in columns, etc. and not being able to know the displayed length (3) versus the technical length (13) is killing me.

Is there some function that returns the 'user-viewed' length?

Upvotes: 0

Views: 225

Answers (2)

Ori Shalom
Ori Shalom

Reputation: 500

You can use the following simple library I wrote for that: https://www.npmjs.com/package/print-colors

It's very lightweight (only one file) and it's not override string prototype or console.log, it's simply let you construct messages with colors by adding the colors as variables to the message, for example:

const c = require('print-colors');

console.log(c.fg.l.red + 'This text will be printed in light red color' + c.e);

console.log(c.fg.d.green + 'This text will be printed in dark green color' + c.e);

console.log(c.bg.d.blue + 'This text will be printed with dark blue background color' + c.e);

console.log(c.bg.l.yellow + c.fg.d.blue + 'This text will be blue with yellow background color' + c.e);

Upvotes: 1

dthree
dthree

Reputation: 20790

I ended up making this function so far:

function viewedLength(str) {
  var re = /\u001b\[\d+m/gm;
  return String(str).replace(re, '').length;
}

Any better or built-in ideas would be appreciated.

Upvotes: 0

Related Questions