printable-characters
A little helper for handling strings containing zero width characters, ANSI styling, whitespaces, newlines, weird Unicode 💩 symbols, etc.
Determining the real (visible) length of a string
const { strlen } = require ('printable-characters')
strlen ('foo bar')
strlen ('\u001b[106mfoo bar\u001b[49m')
Detecting blank text
const { isBlank } = require ('printable-characters')
isBlank ('foobar')
isBlank ('\u001b[106m \t \t \n \u001b[49m')
Obtaining a blank string of the same width
const { blank } = require ('printable-characters')
blank ('💩')
blank ('foo')
blank ('\tfoo \nfoo')
blank ('\u001b[22m\u001b[1mfoo \t\u001b[39m\u001b[22m'))
Matching invisible characters
const { ansiEscapeCodes, zeroWidthCharacters } = require ('printable-characters')
const s = '\u001b[106m' + 'foo' + '\n' + 'bar' + '\u001b[49m'
s.replace (ansiEscapeCodes, '')
.replace (zeroWidthCharacters, '')
Getting the first N visible symbols, preserving the invisible parts
Use for safely truncating strings to maximum width without breaking ANSI codes:
const { first } = require ('printable-characters')
const s = '\u001b[22mfoobar\u001b[22m'
first (s, 0)
first (s, 1)
first (s, 3)
first (s, 6)
const { partition } = require ('printable-characters')
partition ('')
partition ('foo')
partition ('\u001b[1mfoo')
partition ('\u001b[1mfoo\u0000bar')
partition ('\u001b[1mfoo\u0000bar\n')
Applications
- as-table — a simple function that prints objects as ASCII tables
- string.bullet — ASCII-mode bulleting for the list-style data
- string.ify — a fancy pretty printer for the JavaScript entities
- Ololog! — a better
console.log
for the log-driven debugging junkies!
TODO
Handle multi-component emojis, as in this article:
assert.equal (strlen ('👩❤️💋👩'), 1)
assert.equal (blank ('👩❤️💋👩'), ' ')